Selecting and filtering data
- Machine Learning course
- Beginner
- Lesson 16/112
- 5 min
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 rowsDoing 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
import pandas as pd
df = pd.DataFrame({
"ad": ["Ali", "Ece", "Can", "Su"],
"yas": [34, 28, 45, 22],
"maas": [5000, 4200, 7100, 3000],
})
# buraya yazSample solution
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"] > 30 and df["maas"] > 0]</code> error?
- 30 must be text
- It doesn't error
- and needs a single truth value of a Series; & and parentheses are needed Correct answer
- The column doesn't exist
Explanation: For element-wise "and" you write (condition1) & (condition2).
2 Select the first row by position.
ilk = df.____[0]
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 |