How to apply the slicing indexer to the pandas DataFrame.loc attribute?


The loc is an attribute in the pandas DataFrame constructor that is used to access the elements of the DataFrame based on row/column label indexing.

The attribute .loc takes the labels of the DataFrame row and column to access the 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 have applied the slicing indexer to the loc attribute to access the values from the 1 -3 rows. Here, the both start and end values are included.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'Country':['Brazil','Canada','New Zealand','Iceland', 'India', 'Sri Lanka', 'United States'],
'Capital': [ 'Belmopan','Ottawa','Wellington','Reykjavik', 'New Delhi','Colombo', 'Washington D.C']})

print("DataFrame:")
print(df)

# Access the elements using slicing indexer
result = df.loc[1:3]
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
        Country         Capital
0        Brazil        Belmopan
1        Canada          Ottawa
2   New Zealand      Wellington
3       Iceland       Reykjavik
4         India       New Delhi
5     Sri Lanka         Colombo
6 United States  Washington D.C

Output:
      Country    Capital
1      Canada     Ottawa
2 New Zealand Wellington
3     Iceland  Reykjavik

The loc attribute successfully accessed the elements from 3 rows (1-3).

Example 2

Now, we can apply the Slicing indexer for selecting multiple rows labels and a single label from the columns.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']],
columns=['col1','col2'],
index = ['r1','r2','r3','r4'])

print("DataFrame:")
print(df)

# Access the elements using slicing indexer
result = df.loc['r1':'r3','col1']
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
   col1 col2
r1    a    b
r2    c    d
r3    e    f
r4    g    h

Output:
r1    a
r2    c
r3    e
Name: col1, dtype: object

We can notice that both the start and stop of the slice are included for selecting the row labels.

Updated on: 08-Mar-2022

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements