EN VI

pandas Basics: Read, Filter and Group Data in Python

By ··8 min read

Short answer

In pandas, read_csv loads a file into a DataFrame, a table with rows and columns. To keep some rows, we filter with a condition such as orders[orders["status"] == "paid"]. To summarise by group, we use groupby followed by agg. Filter before you group, otherwise cancelled orders stay inside the totals.

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 rows

Filter 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_idn_ordersrevenue
3120000000
4118000000
1115000000
2213000000

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 -> 15000000

Three checks before you trust a table

  1. Print orders.shape and compare it with the number of rows you expect.
  2. Run orders.isna().sum() to count missing values in every column.
  3. Run orders.duplicated("order_id").sum() to count repeated order IDs.

Frequently asked questions

What is a DataFrame in pandas?

A DataFrame is a table with rows and columns, similar to a SQL table or an Excel sheet. Every column has its own data type.

How do I filter rows in pandas?

Write a condition inside square brackets, for example df[df["status"] == "paid"]. Use & and | to combine conditions, and wrap each condition in parentheses.

What is the difference between groupby and a pivot table?

groupby summarises by one or more keys and returns one row per group. A pivot table spreads a second key across columns. Both are available in pandas.

References

Keep learning, step by step.

Each lesson in Learn has a business context, a runnable example and a result check, so you practise this habit on real questions.