CodeBlanks Logo Icon CodeBlanks

Selecting and filtering data

Boolean filtering is used to select rows by condition in a DataFrame.

Filtering with a condition

The boolean mask from NumPy works in pandas too:

genc = df[df["yas"] < 30]
zengin_genc = df[(df["yas"] < 30) & (df["maas"] > 4000)]
print(len(genc))

Parentheses are required when combining conditions with & and |; Python's and/or keywords don't work here.

loc and iloc

loc selects by label, iloc by position; both use the [row, column] form:

df.loc[df["yas"] > 30, "ad"]   # ad column of the matching rows
df.iloc[0]                     # first row
df.iloc[:2, 1]                 # second column of the first two rows

Doing the filter and the column selection in one step with loc is readable and also avoids the "SettingWithCopy" warning.

Practice Filter and select

Select the names of people older than 25 with a salary above 4500 using loc, and print them as a list with tolist().

Starter code

model.py
import pandas as pd

df = pd.DataFrame({
    "ad": ["Ali", "Ece", "Can", "Su"],
    "yas": [34, 28, 45, 22],
    "maas": [5000, 4200, 7100, 3000],
})

# buraya yaz

Sample solution

model.py
import pandas as pd

df = pd.DataFrame({
    "ad": ["Ali", "Ece", "Can", "Su"],
    "yas": [34, 28, 45, 22],
    "maas": [5000, 4200, 7100, 3000],
})

secilen = df.loc[(df["yas"] > 25) & (df["maas"] > 4500), "ad"]
print(secilen.tolist())

Expected output

['Ali', 'Can']

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why does <code>df[df["yas"] &gt; 30 and df["maas"] &gt; 0]</code> error?

  • 30 must be text
  • It doesn't error
  • and needs a single truth value of a Series; &amp; and parentheses are needed Correct answer
  • The column doesn't exist

Explanation: For element-wise "and" you write (condition1) &amp; (condition2).

2 Select the first row by position.

Question
ilk = df.____[0]
Answer
ilk = df.iloc[0]

Explanation: iloc works with integer positions.

3 Match the selectors.

Term Meaning
loc Selection by label
iloc Selection by position
& Element-wise and
| Element-wise or

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation