Pandas Basics

Updated · 5 min read
mediumPython 3.13aipythonpandasdata-cleaningdataframes

pandas is a Python library for working with tables of data. Its main object, the DataFrame, holds rows and columns like a spreadsheet, and it is used to load, clean, filter and summarize data before it goes into an AI model or a chart. Most real AI projects spend more time in pandas than in model code.

This lesson uses 1,000 made-up fee payments for Campus Helper's school, created by code with a fixed seed so that everyone gets the same data.

Creating the Data

Python
import numpy as np
import pandas as pd
 
rng = np.random.default_rng(42)  # a fixed seed, so everyone gets the same data
n = 1000
payments = pd.DataFrame({
    "payment_id": range(1, n + 1),
    "month": rng.choice(pd.period_range("2026-01", "2026-10", freq="M").astype(str), n),
    "item": rng.choice(["tuition", "lab", "field trip", "library"], n, p=[0.4, 0.25, 0.2, 0.15]),
    "method": rng.choice(["card", "bank", "cash"], n),
})
prices = {"tuition": 250.0, "lab": 45.0, "field trip": 30.0, "library": 15.0}
payments["amount"] = payments["item"].map(prices)
payments.loc[rng.choice(n, 30, replace=False), "amount"] = np.nan   # 30 missing amounts
payments.loc[rng.choice(n, 20, replace=False), "method"] = None     # 20 missing methods
payments.to_csv("payments.csv", index=False)
print("Saved", len(payments), "rows")
Output
Saved 1000 rows

Explanation: rng.choice picks random months, items and methods, and the seed 42 makes the "random" choices the same on every computer. Some amounts and methods are then deleted on purpose, because real data always has gaps to clean.

Common Pandas Operations

MethodDescription
pd.read_csv(path)It is used to load a CSV file into a DataFrame
df.head(n)It is used to show the first n rows
df.isna().sum()It is used to count missing values in each column
df["col"].fillna(value)It is used to fill missing values
df[df["col"] > 10]It is used to filter rows by a condition
df.groupby("col")["x"].sum()It is used to total one column for each group

Example: Load, Inspect, Clean, Group

Load, inspect, clean, group
Python
import pandas as pd
 
payments = pd.read_csv("payments.csv")
print(payments.head(3))
print("Missing values:")
print(payments.isna().sum())
 
# Clean: fill a missing amount from the item's price, and mark missing methods
prices = payments.dropna(subset=["amount"]).groupby("item")["amount"].first()
payments["amount"] = payments["amount"].fillna(payments["item"].map(prices))
payments["method"] = payments["method"].fillna("unknown")
 
by_month = payments.groupby("month")["amount"].sum()
print("Total by month:")
print(by_month)
print("Busiest month:", by_month.idxmax(), "with", by_month.max())
Output
   payment_id    month        item method  amount
0           1  2026-01  field trip   cash    30.0
1           2  2026-08     library   cash    15.0
2           3  2026-07     library   cash    15.0
Missing values:
payment_id     0
month          0
item           0
method        20
amount        30
dtype: int64
Total by month:
month
2026-01    11610.0
2026-02    13325.0
2026-03     9650.0
2026-04     9485.0
2026-05    14730.0
2026-06    10680.0
2026-07    12315.0
2026-08    13320.0
2026-09    11680.0
2026-10    12610.0
Name: amount, dtype: float64
Busiest month: 2026-05 with 14730.0

Explanation: isna().sum() finds the 20 missing methods and 30 missing amounts. Each missing amount is filled with its item's price, found from the rows that do have one, and missing methods become "unknown". Finally, groupby("month") totals the amounts for each month: May is the busiest.

Common Mistakes

Dropping rows with missing values without checking how many. You may lose a large share of the data.

Filling every gap with zero. A missing amount isn't a $0 payment.

Forgetting to save the cleaned data. Use to_csv() so the next step uses it.

Interview Corner

What is a pandas DataFrame?

A table of rows and labeled columns, used to load, clean, filter, group and summarize data in Python.

How do you handle missing values?

First count them with isna().sum(), then decide per column: fill from a related value, use a sensible default, label them as unknown, or drop rows, depending on what the data means.

Practice

Exercise: the 1,000-payment checkpoint. Create payments.csv with the first program, then load it, clean the missing values, and total payments by item and by method. Which item brings in the most money, and how many payments have an unknown method?

Check your understanding:

  1. What does isna().sum() show?
  2. How were missing amounts filled, and why?
  3. What does groupby("month")["amount"].sum() produce?

Quick check: pandas basics

4 questions
1Which function loads a CSV file?
2How many amounts were missing?
3Why weren't missing amounts filled with 0?
4Which was the busiest month?

Key Takeaways

Quick reference

TaskCode
Loadpd.read_csv("file.csv")
Lookdf.head()
Missingdf.isna().sum()
Filldf["col"].fillna(value)
Groupdf.groupby("a")["b"].sum()

Was this tutorial helpful?

Lesson 79 of 186