Python for Artificial Intelligence Advanced 15 minutes

Pandas

Working with tabular data: DataFrame, selection, filtering, grouping and missing values.

Your progress in the track0%

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 columns

Selecting 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

  1. What is the difference between loc and iloc?

    loc selects by labels (row and column names), and iloc selects by numerical positions.

  2. How do you find the number of missing values in each column?

    df.isna().sum().

Sources and references

  1. 10 minutes to pandas — pandas documentation
  2. Group by: split-apply-combine — pandas documentation
  3. Wes McKinney — Python for Data Analysis, 3E (open access)

Complete the lesson