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


The “.loc” is an attribute of the pandas.Series object which is used to access elements from series based on label indexing. And It works similar to pandas.Series “at” attribute but the difference is, the “at” attribute accesses only a single element whereas the “loc” attribute can access a group of elements using labels.

The “loc” attribute accesses the labels based on labels and it also supports slicing object with labels.

Example 1

import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white','R':'red', 'Bl':'blue','G':'green'})
print(series)

print("Output: ")
print(series.loc['B'])

Explanation

In this following example, we created a pandas series object “series” using a python dictionary with pairs of keys and values. Here the index labels are created by using keys in the dictionary.

Output

B  black
W  white
R    red
Bl  blue
G  green
dtype: object

Output:
black

We have successfully accessed a single element from pandas.Series object ”series” by using the label “B”. The label “B” is given to the loc attribute.

Example 2

import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white','R':'red', 'Bl':'blue','G':'green'})
print(series)

print("Output: ")
print(series.loc['B':'G'])

Explanation

In the following example, we will access the group of elements from the pandas.Series object by providing a slicing object to the “loc” attribute.

Output

B  black
W  white
R    red
Bl  blue
G  green
dtype: object

Output:
B  black
W  white
R    red
Bl  blue
G  green
dtype: object

We have accessed the group of pandas.Series elements by using the “loc” attribute. And we got another series object as a result which is displayed in the above output block. It will raise KeyError if the provided labels are not present in the series object.

Updated on: 09-Mar-2022

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements