In the first post of this series we met the DataFrame, the table object that pandas adds to Python. Now we use it on a small order table. On a file with a few hundred thousand rows, we cannot read every line by eye, so we ask for a shape, a filter and a summary instead. These three steps cover most first-pass analysis, and the code runs as written.
Read a file and look before you calculate
To load a CSV file, we use read_csv. To turn a text column into real dates, we pass parse_dates. In your own work, replace the io.StringIO part with the file name, for example "orders.csv". Right after reading, we print the shape, which is the number of rows and columns, and the first rows.
import io
import pandas as pd
csv = io.StringIO("""order_id,customer_id,total_amount,status,order_date
1001,1,15000000,paid,2026-10-01
1002,2,8000000,paid,2026-10-03
1003,1,12000000,cancelled,2026-10-05
1004,3,20000000,paid,2026-10-08
1005,2,5000000,paid,2026-10-12
1006,4,18000000,paid,2026-10-15
""")
orders = pd.read_csv(csv, parse_dates=["order_date"])
print(orders.shape) # (6, 5)
print(orders.head(3)) # the first three rowsFilter rows with a condition
This is the same job as WHERE in SQL. We write a condition inside square brackets, and pandas keeps the rows where it is true. Here we keep the paid orders.
paid = orders[orders["status"] == "paid"]
print(paid.shape) # (5, 5)We went from 6 rows to 5, because order 1003 is cancelled. Combine conditions with & for and, and | for or, and put each condition in its own parentheses.
Group and summarise
This is a group-and-summarise problem, the same as GROUP BY in SQL. To count and add up orders per customer, we use groupby and then agg. Each argument of agg has the form new_name=("column", "function").
summary = (
paid.groupby("customer_id")
.agg(n_orders=("order_id", "count"), revenue=("total_amount", "sum"))
.reset_index()
.sort_values("revenue", ascending=False)
)
print(summary)| customer_id | n_orders | revenue |
|---|---|---|
| 3 | 1 | 20000000 |
| 4 | 1 | 18000000 |
| 1 | 1 | 15000000 |
| 2 | 2 | 13000000 |
The reset_index call turns the group key back into a normal column. Without it, customer_id becomes the row label, which is fine for reading but awkward for a later merge.
The filter trap: totals that include cancelled orders
Grouping the full table looks correct, and pandas shows no warning. The cancelled order is still inside the group, so customer 1 appears with 27,000,000 instead of 15,000,000.
# WRONG: cancelled order 1003 is still inside the group
print(orders.groupby("customer_id")["total_amount"].sum()) # customer 1 -> 27000000
# right: filter first, then group
print(paid.groupby("customer_id")["total_amount"].sum()) # customer 1 -> 15000000Three checks before you trust a table
- Print
orders.shapeand compare it with the number of rows you expect. - Run
orders.isna().sum()to count missing values in every column. - Run
orders.duplicated("order_id").sum()to count repeated order IDs.


