Pandas is de standaardbibliotheek voor het werken met tabelgegevens in Python. De twee centrale datastructuren zijn:
DataFrame: een tweedimensionale tabel met benoemde kolommen en een index (vergelijkbaar met een spreadsheet of SQL-tabel)Series: een eendimensionale gelabelde array โ elke kolom van een DataFrame is een Series
In deze notebook leer je DataFrames aanmaken, inladen en inspecteren.
import numpy as np
import pandas as pd
print(pd.__version__)2.3.3
data = {
"name": ["Alice", "Bob", "Charlie", "Diana"],
"age": [22, 25, 23, 21],
"score": [88.5, 74.0, 92.3, 81.7],
"passed": [True, True, True, True],
}
df = pd.DataFrame(data)
dfEen CSV-bestand inladenยถ
In de praktijk lees je data bijna altijd uit een bestand of een externe bron. Hier gebruiken we de Titanic-dataset van Seaborn โ een klassieker in data-analyse.
import seaborn as sns
# Load the Titanic dataset (automatically downloaded on first run)
titanic = sns.load_dataset("titanic")
# Or from a CSV file:
# df = pd.read_csv("path/to/file.csv")
titanic.head()Een DataFrame inspecterenยถ
Dit zijn de eerste stappen die je bij elke nieuwe dataset uitvoert.
# View first and last rows
print(titanic.head(5)) # first 5 rows
print()
print(titanic.tail(3)) # last 3 rows survived pclass sex age sibsp parch fare embarked class \
0 0 3 male 22.0 1 0 7.2500 S Third
1 1 1 female 38.0 1 0 71.2833 C First
2 1 3 female 26.0 0 0 7.9250 S Third
3 1 1 female 35.0 1 0 53.1000 S First
4 0 3 male 35.0 0 0 8.0500 S Third
who adult_male deck embark_town alive alone
0 man True NaN Southampton no False
1 woman False C Cherbourg yes False
2 woman False NaN Southampton yes True
3 woman False C Southampton yes False
4 man True NaN Southampton no True
survived pclass sex age sibsp parch fare embarked class \
888 0 3 female NaN 1 2 23.45 S Third
889 1 1 male 26.0 0 0 30.00 C First
890 0 3 male 32.0 0 0 7.75 Q Third
who adult_male deck embark_town alive alone
888 woman False NaN Southampton no False
889 man True C Cherbourg yes True
890 man True NaN Queenstown no True
# Dimensions
print("shape:", titanic.shape) # (rows, columns)
print("rows: ", len(titanic))shape: (891, 15)
rows: 891
# Column names
print(titanic.columns.tolist())['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town', 'alive', 'alone']
# Data type of each column
print(titanic.dtypes)survived int64
pclass int64
sex object
age float64
sibsp int64
parch int64
fare float64
embarked object
class category
who object
adult_male bool
deck category
embark_town object
alive object
alone bool
dtype: object
# Concise summary: types + non-null counts
titanic.info()<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 survived 891 non-null int64
1 pclass 891 non-null int64
2 sex 891 non-null object
3 age 714 non-null float64
4 sibsp 891 non-null int64
5 parch 891 non-null int64
6 fare 891 non-null float64
7 embarked 889 non-null object
8 class 891 non-null category
9 who 891 non-null object
10 adult_male 891 non-null bool
11 deck 203 non-null category
12 embark_town 889 non-null object
13 alive 891 non-null object
14 alone 891 non-null bool
dtypes: bool(2), category(2), float64(2), int64(4), object(5)
memory usage: 80.7+ KB
# Statistical summary of numeric columns
titanic.describe()# Include categorical columns โ .T transposes for readability
titanic.describe(include="all").TSeries vs. DataFrameยถ
Een Series is een eendimensionale kolom; een DataFrame is een verzameling Series die een gemeenschappelijke index delen.
# Selecting one column returns a Series
ages = titanic["age"]
print(type(ages)) # <class 'pandas.core.series.Series'>
print(ages.dtype) # float64
print(ages.head())<class 'pandas.core.series.Series'>
float64
0 22.0
1 38.0
2 26.0
3 35.0
4 35.0
Name: age, dtype: float64
# Selecting multiple columns returns a DataFrame
selected = titanic[["survived", "age", "fare"]]
print(type(selected)) # <class 'pandas.core.frame.DataFrame'>
selected.head()<class 'pandas.core.frame.DataFrame'>
# Access the underlying NumPy array
print(ages.values[:5]) # numpy.ndarray
print(type(ages.values))[22. 38. 26. 35. 35.]
<class 'numpy.ndarray'>
Ontbrekende waarden snel verkennenยถ
# Number of missing values per column
print(titanic.isnull().sum())survived 0
pclass 0
sex 0
age 177
sibsp 0
parch 0
fare 0
embarked 2
class 0
who 0
adult_male 0
deck 688
embark_town 2
alive 0
alone 0
dtype: int64
# Percentage of missing values
pct = titanic.isnull().mean() * 100
print(pct[pct > 0].round(1)) # show only columns with missing valuesage 19.9
embarked 0.2
deck 77.2
embark_town 0.2
dtype: float64
import seaborn as sns
penguins = sns.load_dataset("penguins")Oefening 1 โ Druk de eerste 8 rijen af. Hoeveel rijen en kolommen bevat de dataset?
# your solution hereOefening 2 โ Gebruik .info() en .dtypes om te bepalen: welke kolommen zijn numeriek en welke zijn categorisch?
# your solution hereOefening 3 โ Gebruik .describe() om te bepalen: wat zijn het gemiddelde en de mediaan van bill_length_mm? (Tip: mediaan = 50% in de output van describe())
# your solution hereOefening 4 โ Bepaal voor elke kolom het aantal en het percentage ontbrekende waarden. Welke kolom heeft de meeste ontbrekende waarden?
# your solution hereOefening 5 โ Selecteer de kolommen species, bill_length_mm en body_mass_g en bewaar ze in een nieuw DataFrame df_sub. Controleer het type van het resultaat.
# your solution here