How to access pandas DataFrame elements using the .loc attribute?


The “.loc” is an attribute of the pandas.DataFrame. it is used to access elements from DataFrame based on row/column label indexing. And It works similar to pandas.DataFrame “at” attribute but the difference is, the “at” attribute is used to access only a single element whereas the “loc” attribute can access a group of elements.

The “.loc” attribute allows inputs like an integer value, a list of integer values, and a slicing object with integers, and boolean array, etc. And it will raise a KeyError if the specified label is not found in the DataFrame.

Example 1

In this following example, we created a pandas DataFrame “df” using a python dictionary with pairs of keys and values. Here, the index labels are specified by using index parameters.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'B':['black','Blue'], 'W':['white','wine'],'R':['red', 'rose dust'],'G':['green','gray']},
index=['row1','row2'])

print("DataFrame:")
print(df)

# get the elements by labels
result = df.loc['row2', 'W']
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
        B      W          R       G
row1 black  white       red   green
row2  Blue   wine  rose dust   gray

Output:
wine

We have successfully accessed a single element from the DataFrame ”df” by specifying row/column labels to the loc attribute.

Example 2

Here, we will access the group of elements from the pandas.DataFrame by providing a list of labels to the “loc” attribute.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'B':['black','Blue'], 'W':['white','wine'],'R':['red', 'rose dust'],'G':['green','gray']},
index=['row1','row2'])

print("DataFrame:")
print(df)

# set the elements by labels
result = df.loc[['row1','row2']]
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
        B     W         R     G
row1 black white       red green
row2  Blue  wine rose dust  gray

Output:
         B    W         R      G
row1 black white      red   green
row2  Blue  wine rose dust   gray

The loc attribute successfully accessed the two rows (row1 and row2) elements from the pandas DataFrame using the “loc” attribute. as a result, it returns a new DataFrame which is displayed in the above output block.

Updated on: 08-Mar-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements