Javatpoint Logo
Javatpoint Logo

Pandas DataFrame.loc[]

The DataFrame.loc[] is used to retrieve the group of rows and columns by labels or a boolean array in the DataFrame. It takes only index labels, and if it exists in the caller DataFrame, it returns the rows, columns, or DataFrame.

The DataFrame.loc[] is a label based but may use with the boolean array.

The allowed inputs for .loc[] are:

  • Single label, e.g.,7 or a. Here, 7 is interpreted as the label of the index.
  • List or array of labels, e.g. ['x', 'y', 'z'].
  • Slice object with labels, e.g. 'x':'f'.
  • A boolean array of the same length. e.g. [True, True, False].
  • callable function with one argument.

Syntax

Parameters

None

Returns

It returns Scalar, Series or DataFrame.

Example

# importing pandas as pd

Output:

William

Example2:

Output:

P         Q      R         S
A   28.0    15.0    11   41.0
B   17.0    23.0    23   NaN
C   14.0    NaN    16   34.0
D   42.0   15.0     32   25.0
E NaN    12.0    42   18.0

Now, we have to use DataFrame.loc attribute to return the values present in the DataFrame.

Output:

    P    S
A 28.0  41.0
B 17.0   NaN
C14.0  34.0
D  42.0  25.0
ENaN  18.0

Next TopicPandas loc vs iloc




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA