Skip to content
Justice Tech School

Select with loc

loc selects by label for rows and columns. Slices with loc include both ends.

Example
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['Ada', 'Bob', 'Cy', 'Di'], 'age': [30, 25, 35, 28], 'city': ['Lagos', 'Accra', 'Lagos', 'Nairobi'], 'score': [88.5, 92.0, 79.5, 85.0]})
x = df.set_index('name')
print(x.loc['Ada', 'score'])
print(x.loc['Bob':'Di', ['age', 'city']])

Result

88.5
      age     city
name              
Bob    25    Accra
Cy     35    Lagos
Di     28  Nairobi

Exercise

Select by label.

df.[0, "name"]

Quiz Test

Is the loc slice end included?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.