Filtering rows
Keep only the rows that match a condition.
To keep only some rows, write a condition on a column, such as weather["high"] >= 25. That produces a Series of True/False values, one per row, called a boolean mask. Putting the mask inside the brackets, weather[mask], keeps only the rows where it is True. Filtering is how you answer questions like "which months were hot?" or "how many coffee sales were there?"
import io
import pandas as pd
csv_text = """month,high,low,rain_mm
Jan,8,1,78
Feb,10,2,60
Mar,14,5,55
Apr,18,8,42
May,23,12,35
Jun,28,17,20
Jul,31,20,12
Aug,30,19,15
Sep,26,15,30
Oct,20,10,58
Nov,13,5,72
Dec,9,2,85
"""
weather = pd.read_csv(io.StringIO(csv_text))
hot = weather["high"] >= 25
print(hot.head(7))
hot_months = weather[hot]
print(hot_months[["month", "high"]])
print(len(hot_months), "hot months")hot is True for Jun, Jul, Aug and Sep. weather[hot] keeps those 4 rows. Most people write it in one line: weather[weather["high"] >= 25].
Use == to compare (two equals signs). A single = is assignment and gives a syntax error inside brackets.
Text comparisons are exact: "coffee" does not equal "Coffee".