In deze notebook leer je de meest gebruikte technieken om rijen en kolommen te selecteren uit een DataFrame:
Kolomselectie
Boolean filtering โ de primaire manier om rijen te filteren
.loc[]en.iloc[]โ voor label- en positie-gebaseerde selectieSorteren en tellen
Alle technieken worden intensief gebruikt in de latere ML-notebooks.
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset("titanic")
titanic.head()Kolomselectieยถ
# One column โ Series
ages = titanic["age"]
print(type(ages))
ages.head()<class 'pandas.core.series.Series'>
0 22.0
1 38.0
2 26.0
3 35.0
4 35.0
Name: age, dtype: float64# Multiple columns โ DataFrame (double square brackets)
selected = titanic[["survived", "pclass", "age", "fare"]]
selected.head()Boolean filteringยถ
Filtering werkt net als bij NumPy: je maakt een masker van True/False-waarden en past het toe op het DataFrame.
Combineer condities met:
&(AND)|(OR)~(NOT)
โ ๏ธ Zet elke conditie tussen haakjes wanneer je combineert.
# Simple condition
women = titanic[titanic["sex"] == "female"]
print(f"Number of women: {len(women)}")
women.head()Number of women: 314
# Combine multiple conditions with &
first_class_survivors = titanic[(titanic["survived"] == 1) & (titanic["pclass"] == 1)]
print(f"First-class survivors: {len(first_class_survivors)}")First-class survivors: 136
# Combine with | โ passengers in 1st or 2nd class
first_or_second = titanic[(titanic["pclass"] == 1) | (titanic["pclass"] == 2)]
print(len(first_or_second))
# Alternative with .isin()
first_or_second_v2 = titanic[titanic["pclass"].isin([1, 2])]
print(len(first_or_second_v2))400
400
# Comparison with numeric threshold
minors = titanic[titanic["age"] < 18]
print(f"Minors on board: {len(minors)}")Minors on board: 113
.loc[] โ label-gebaseerde selectieยถ
Met .loc[rows, columns] selecteer je op basis van indexlabels en kolomnamen.
# Select rows 5 through 9, columns 'survived', 'age' and 'sex'
titanic.loc[5:9, ["survived", "age", "sex"]]# .loc with boolean mask + column selection
# Returns surviving women with their age and class
titanic.loc[
(titanic["survived"] == 1) & (titanic["sex"] == "female"), ["age", "pclass", "fare"]
].head().iloc[] โ positie-gebaseerde selectieยถ
Met .iloc[rows, columns] selecteer je op basis van gehele getallen (positie, 0-gebaseerd). Handig wanneer je de kolomnamen niet kent.
# First 5 rows, columns 0 through 3
titanic.iloc[0:5, 0:4]# Last row
titanic.iloc[-1]survived 0
pclass 3
sex male
age 32.0
sibsp 0
parch 0
fare 7.75
embarked Q
class Third
who man
adult_male True
deck NaN
embark_town Queenstown
alive no
alone True
Name: 890, dtype: objectSorterenยถ
# Sort by one column (descending)
titanic.sort_values("fare", ascending=False).head()# Sort by multiple columns
titanic.sort_values(["pclass", "fare"], ascending=[True, False]).head(8)Unieke waarden tellenยถ
# Unique values in a column
print(titanic["pclass"].unique())
print(titanic["sex"].nunique(), "unique values in 'sex'")[3 1 2]
2 unique values in 'sex'
# Count occurrences
print(titanic["pclass"].value_counts())
print()
# As proportions
print(titanic["survived"].value_counts(normalize=True).round(2))pclass
3 491
1 216
2 184
Name: count, dtype: int64
survived
0 0.62
1 0.38
Name: proportion, dtype: float64
Index resettenยถ
Na filtering klopt de index van het resulterende DataFrame niet meer aaneengesloten. Gebruik .reset_index(drop=True) om de index opnieuw te nummeren.
women = titanic[titanic["sex"] == "female"].reset_index(drop=True)
print(women.index[:5].tolist()) # [0, 1, 2, 3, 4][0, 1, 2, 3, 4]
tips = sns.load_dataset("tips")
tips.head()Oefening 1 โ Selecteer alle rijen waar sex == "Female" รฉn smoker == "No". Hoeveel rijen zijn er?
# your solution hereOefening 2 โ Gebruik .isin() om alle rijen te selecteren waar day gelijk is aan "Sat" of "Sun". Bereken het gemiddelde fooi (tip) voor die rijen.
# your solution hereOefening 3 โ Selecteer met .loc[] de kolommen total_bill en tip voor rijen 10 t/m 19. Bereken de fooi als percentage van de rekening voor die rijen en voeg het toe als nieuwe kolom.
# your solution hereOefening 4 โ Gebruik .value_counts() om te bepalen: op welke dag van de week is er de meeste activiteit (meeste bezoeken)? En wat is de meest voorkomende partijgrootte (size)?
# your solution hereOefening 5 โ Sorteer de tips-dataset op total_bill van hoog naar laag en selecteer de top-10. Wat zijn de gemiddelde fooi en het gemiddeld percentage bij de top-10?
# your solution here