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
citiesthat contains "London" and "Paris". - Use
[]subsetting to filtertemperaturesfor rows where thecitycolumn takes a value in thecitieslist. - Use
.loc[]subsetting to filtertemperatures_indfor rows where the city is in thecitieslist.
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[____])