pandas.Series.loc

Access a group of rows and columns by label(s) or a boolean array.

.loc[] is primarily label based, but may also be used with a boolean array.

Allowed inputs are:

  • A single label, e.g. 5 or 'a', (note that 5 is

    interpreted as a label of the index, and never as an integer position along the index).

  • A list or array of labels, e.g. ['a', 'b', 'c'].

  • A slice object with labels, e.g. 'a':'f'.

Warning

Note that contrary to usual python slices, both the start and the stop are included

  • A boolean array of the same length as the axis being sliced,

    e.g. [True, False, True].

  • A callable function with one argument (the calling Series or

    DataFrame) and that returns valid output for indexing (one of the above)

See more at Selection by Label

raises
KeyError:

when any items are not found

Limitations

  • Loc always returns Series.

  • Loc slice is supported only with numeric values and specified start.

  • Loc callable is not supported yet.

  • This function may reveal slower performance than Pandas* on user system. Users should exercise a tradeoff

    between staying in JIT-region with that function or going back to interpreter mode.

Examples

With a scalar integer. Returns single value.
import numpy as np
import pandas as pd
from numba import njit


@njit
def series_loc_value():
    series = pd.Series([5, 4, 3, 2, 1], index=[0, 2, 4, 6, 8])

    return series.loc[4]


print(series_loc_value())
$ python ./series/series_loc/series_loc_single_result.py
4    3
dtype: int64
With a scalar integer. Returns multiple value.
import numpy as np
import pandas as pd
from numba import njit


@njit
def series_loc_many_idx():
    series = pd.Series([5, 4, 3, 2, 1], index=[0, 2, 0, 6, 0])

    return series.loc[0]


print(series_loc_many_idx())
$ python ./series/series_loc/series_loc_multiple_result.py
0    5
0    3
0    1
dtype: int64
With a slice object. Returns multiple value.
import numpy as np
import pandas as pd
from numba import njit


@njit
def series_loc_slice():
    series = pd.Series([5, 4, 3, 2, 1])

    return series.loc[1:3]


print(series_loc_slice())
$ python ./series/series_loc/series_loc_slice.py
1    4
2    3
3    2
dtype: int64

See also

DataFrame.at

Access a single value for a row/column label pair.

DataFrame.iloc

Access group of rows and columns by integer position(s).

DataFrame.xs

Returns a cross-section (row(s) or column(s)) from the Series/DataFrame.

Series.loc

Access group of values using labels.