← Learning Hub
Beginner

Selecting and Filtering Rows

Most analysis starts by narrowing the data: only this city, only big orders, only last month. pandas uses boolean conditions to keep matching rows, and loc/iloc to pick rows and columns by label or position.

Filtering with conditions

Example
You can edit this code.

Several conditions

Use & (and), | (or), ~ (not), with brackets around each part:

Example
You can edit this code.

loc and iloc

  • df.loc[rows, columns] - by labels (row index labels and column names)
  • df.iloc[rows, columns] - by position (0, 1, 2...)
Example
You can edit this code.

query: filters as text

Example
You can edit this code.

Sorting

Example
You can edit this code.
Key points
  • df[condition] keeps matching rows.
  • Use & | ~ with brackets for several conditions.
  • loc uses labels; iloc uses positions.

📝 Test yourself

1. Which symbol means 'and' between pandas conditions?
2. What does iloc use?
3. Fill in the method that keeps rows whose city is in a list:
df[df["city"].(["Pune", "Delhi"])]