Get startedGet started for free

Subsetting with .loc[]

The killer feature for indexes is .loc[]: a subsetting method that accepts index values. When you pass it a single argument, it will take a subset of rows.

The code for subsetting using .loc[] can be easier to read than standard square bracket subsetting, which can make your code less burdensome to maintain.

pandas is loaded as pd. temperatures and temperatures_ind are available; the latter is indexed by city.

This exercise is part of the course

Data Manipulation with pandas

View Course

Exercise instructions

  • Create a list called cities that contains "Moscow" and "Saint Petersburg".
  • Use [] subsetting to filter temperatures for rows where the city column takes a value in the cities list.
  • Use .loc[] subsetting to filter temperatures_ind for rows where the city is in the cities list.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Make a list of cities to subset on
cities = ["____", "____"]

# Subset temperatures using square brackets
print(temperatures[____])

# Subset temperatures_ind using .loc[]
print(temperatures_ind.loc[____])
Edit and Run Code