Pandas
Working with tabular data: DataFrame, selection, filtering, grouping and missing values.
Series and DataFrame
import pandas as pd
df = pd.DataFrame({
"name": ["Ali", "Mona", "Omar", "Huda"],
"age": [23, 31, None, 27],
"track": ["ML", "DL", "ML", "NLP"],
"score": [78, 92, 65, 88],
})
df.head()
df.info() # types and non-missing values
df.describe() # descriptive statistics for numeric columnsSelecting data
df["score"] # Series
df[["name", "score"]] # DataFrame
df.loc[0, "name"] # by label
df.iloc[0:2, 1:3] # by position
df[df["score"] >= 80] # conditional filtering
df.query("track == 'ML' and score > 60")Missing values
df.isna().sum() # number of missing values per column
df["age"] = df["age"].fillna(df["age"].median())
df_clean = df.dropna()The decision to drop or impute missing values affects the results, and imputation values must be computed from the training data only when building a model, to avoid data leakage.
New columns and transformations
df["passed"] = df["score"] >= 70
df["track"] = df["track"].astype("category")
df.sort_values("score", ascending=False)Grouping
df.groupby("track")["score"].agg(["mean", "count"])splits the data by track, and computes the mean and count for each group.
Merging
tracks = pd.DataFrame({"track": ["ML", "DL", "NLP"],
"hours": [40, 50, 45]})
merged = df.merge(tracks, on="track", how="left")A performance tip
Avoid iterating over rows with iterrows on large data, and use operations on whole columns, because they are vectorized and much faster.
Lesson terms
- DataFrame
- A two-dimensional table with named columns and a row index, whose columns may have different types.
- Grouping
- Splitting the data by the values of a column, applying a summary function to each group, and combining the results.
- Chaining
- A one-dimensional array with an index, representing a single column of a DataFrame.
Abstract
pandas is a library for analysing tabular data that offers two core structures: Series for a single column and DataFrame for a table. It allows reading data from many sources, selecting rows and columns with loc and iloc, conditional filtering, handling missing values, grouping with groupby, and merging tables.
Review questions
-
What is the difference between loc and iloc?
loc selects by labels (row and column names), and iloc selects by numerical positions.
-
How do you find the number of missing values in each column?
df.isna().sum().
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate