Paul's Python CoursePPC

Selecting and filtering rows

Not met yet

A condition on a column, like census["age"] > 80, gives a Series of True and False. Put it inside census[...] and you keep the rows marked True. Combine conditions with & (and), | (or) and ~ (not), with brackets round each one; Python's and won't work on a Series. Filtered rows keep their original labels, so .loc finds rows by label and .iloc by position.

Try it

main.py
import pandas as pd

people = pd.DataFrame({
    "name": ["Edith Hart", "Walter Lee", "Mary Lee", "Sam Lee"],
    "parish": ["Hill", "Market", "Market", "Market"],
    "age": [34, 88, 52, 9],
})
older = people[(people["age"] > 50) & (people["parish"] == "Market")]
print(older)
print(older.iloc[0]["name"], older.loc[2, "name"])

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks Python's and combines two True/False columns row by row. It needs &, with brackets round each condition.
  • Thinks and between two True/False columns quietly uses one of them, so the filter works on the second condition alone.
  • Thinks filtering renumbers the rows from 0. Rows keep the labels they had in the original table.
  • Thinks .loc on a filtered table looks rows up in the table it came from.
  • Thinks comparing a column of numbers with text such as "1951" still finds the matching rows.

Where it comes up