Learn / Python for AI / Lesson 2

pandas for data analysis

14 min Tested on Python 3.15Updated By
In short

pandas is Python's spreadsheet: a DataFrame is a table with named columns that you can load from CSV, Excel, SQL or JSON. You select columns with df["col"], filter rows with conditions, summarise with groupby, and clean missing values — the everyday work behind every data analysis and AI project.

A first DataFrame

Python
import pandas as pd

df = pd.DataFrame({
    "city": ["Pune", "Ghent", "Pune", "Brussels", "Ghent"],
    "product": ["tea", "tea", "coffee", "coffee", "cake"],
    "units": [30, 12, 25, 40, 8],
    "price": [2.5, 3.0, 3.5, 3.2, 4.0],
})
print(df.head(3))
print(df.shape)
Output
    city product  units  price
0   Pune     tea     30    2.5
1  Ghent     tea     12    3.0
2   Pune  coffee     25    3.5
(5, 4)

Reading a CSV file

Python
import io
import pandas as pd

csv_text = """date,region,revenue
2026-01-05,EU,1200
2026-01-06,IN,900
2026-01-06,EU,
2026-01-07,IN,1500
"""
df = pd.read_csv(io.StringIO(csv_text), parse_dates=["date"])
print(df)
print(df["revenue"].isna().sum(), "missing value")
Output
        date region  revenue
0 2026-01-05     EU   1200.0
1 2026-01-06     IN    900.0
2 2026-01-06     EU      NaN
3 2026-01-07     IN   1500.0
1 missing value

On your computer you'd write pd.read_csv("sales.csv"). Here we read from a string so it runs in the browser. Empty cells become NaN ("not a number").

Selecting and filtering

Python
import pandas as pd

df = pd.DataFrame({
    "city": ["Pune", "Ghent", "Pune", "Brussels", "Ghent"],
    "product": ["tea", "tea", "coffee", "coffee", "cake"],
    "units": [30, 12, 25, 40, 8],
    "price": [2.5, 3.0, 3.5, 3.2, 4.0],
})
print(df["units"].sum())
print(df[["city", "units"]].tail(2))

big = df[(df["units"] > 10) & (df["product"] == "coffee")]
print(big)
Output
115
       city  units
3  Brussels     40
4     Ghent      8
       city product  units  price
2      Pune  coffee     25    3.5
3  Brussels  coffee     40    3.2

New columns, groupby and sorting

Python
import pandas as pd

df = pd.DataFrame({
    "city": ["Pune", "Ghent", "Pune", "Brussels", "Ghent"],
    "product": ["tea", "tea", "coffee", "coffee", "cake"],
    "units": [30, 12, 25, 40, 8],
    "price": [2.5, 3.0, 3.5, 3.2, 4.0],
})
df["revenue"] = df["units"] * df["price"]

by_city = df.groupby("city")["revenue"].sum().sort_values(ascending=False)
print(by_city)

summary = df.groupby("product").agg(units=("units", "sum"), avg_price=("price", "mean"))
print(summary)
Output
city
Pune        162.5
Brussels    128.0
Ghent        68.0
Name: revenue, dtype: float64
         units  avg_price
product                  
cake         8       4.00
coffee      65       3.35
tea         42       2.75

Cleaning missing values

Python
import pandas as pd

df = pd.DataFrame({"name": ["Ana", "Ben", None, "Dev"], "age": [31, None, 28, 45]})
print(df.dropna())
print(df.fillna({"name": "unknown", "age": df["age"].median()}))
Output
  name   age
0  Ana  31.0
3  Dev  45.0
      name   age
0      Ana  31.0
1      Ben  31.0
2  unknown  28.0
3      Dev  45.0

Real data always has gaps. Decide per column: drop rows, fill with a sensible value (the median is robust to outliers), or keep the gap and handle it later. Machine learning models usually need no missing values at all.

Practice

For the orders below, add a total column (qty * unit_price), then print the total revenue per customer as a Series sorted from highest to lowest.

Expected output:
customer
Ben     75.0
Ana     50.0
Cara    20.0
Name: total, dtype: float64
Your code

Quick check

1. How do you keep rows where units is above 10?

2. What does df.groupby("city")["revenue"].sum() return?

3. Empty cells in a CSV become...

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →