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
Exercise instructions
- Create a list called
cities
that contains "Moscow" and "Saint Petersburg". - Use
[]
subsetting to filtertemperatures
for rows where thecity
column takes a value in thecities
list. - Use
.loc[]
subsetting to filtertemperatures_ind
for rows where the city is in thecities
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[____])