Data Analysis · pandas Core · lesson 7 of 12
Filtering and sorting
about 14 minutes · free · runs in your browser
Selecting rows by condition
Filtering a DataFrame uses the same boolean masks as NumPy:
df[df["temp"] > 20]
df[(df["temp"] > 10) & (df["city"] != "Oslo")]
The same rule applies: & and |, never and and or, and brackets around
each condition.
Two conveniences worth knowing:
df[df["city"].isin(["London", "Oslo"])] # membership
df[df["city"].str.startswith("L")] # string methods live under .str
Sorting returns a new frame:
df.sort_values("temp") # ascending
df.sort_values("temp", ascending=False) # descending
df.sort_values(["band", "temp"]) # by two columns
Your turn: select the cities above 10 degrees, and produce the city names ordered from warmest to coldest.
You start from this, and edit it in the browser:
import pandas as pd
df = pd.DataFrame({
"city": ["London", "Lisbon", "Oslo", "Tokyo", "Nairobi"],
"temp": [14, 24, 3, 19, 26],
})
# Set mild (a DataFrame) and warmest_first (a list of city names).