Skip to content

pandas is the Python library for working with tables in memory. Its DataFrame holds rows and typed columns, and its methods do what SQL does with SELECT, WHERE, GROUP BY, JOIN, and window functions. This pandas tutorial is for analytics engineers and analysts who already write SQL: it builds two small tables, then filters, aggregates, joins, and resamples them, and reads and writes CSV, JSON, and Parquet files. Every result shown is real output from pandas 3.1.1, and the places where it differs from PostgreSQL on the same rows are listed.

Install pandas and build two tables

Install pandas from PyPI with pip, or from conda-forge with conda. The parquet extra adds PyArrow, the package pandas uses to read and write Parquet files.

pip install "pandas[parquet]"

A DataFrame is a two-dimensional labeled table whose columns can have different types. The pandas documentation compares it to a spreadsheet or a SQL table. A Series is a single labeled column. The labels are the index, and by default they are the row numbers printed at the left of each result below. This code builds both tables, so you can paste it into a Python session or a notebook:

import pandas as pd

customers = pd.DataFrame({
    "customer_id": [1, 2, 3, 4, 5],
    "customer_name": ["Acme Retail", "Borealis Labs", "Cobalt Foods",
                      "Dune Travel", "Elm Studio"],
    "country": ["US", "CA", "US", None, "DE"],
})

orders = pd.DataFrame({
    "order_id": [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008],
    "customer_id": [1, 2, 1, 3, 2, 3, 4, 1],
    "order_date": ["2026-03-02", "2026-03-03", "2026-03-05", "2026-03-09",
                   "2026-03-15", "2026-03-24", "2026-04-01", "2026-04-03"],
    "status": ["completed", "completed", "refunded", "completed",
               "completed", "pending", "completed", "completed"],
    "amount": [120.00, 75.50, 40.00, 310.00, 220.00, None, 18.50, 260.00],
})
orders["order_date"] = pd.to_datetime(orders["order_date"])

print(orders)
   order_id  customer_id order_date     status  amount
0      1001            1 2026-03-02  completed   120.0
1      1002            2 2026-03-03  completed    75.5
2      1003            1 2026-03-05   refunded    40.0
3      1004            3 2026-03-09  completed   310.0
4      1005            2 2026-03-15  completed   220.0
5      1006            3 2026-03-24    pending     NaN
6      1007            4 2026-04-01  completed    18.5
7      1008            1 2026-04-03  completed   260.0

Three details matter later: order 1006 has no amount (printed as NaN), Dune Travel has no country, and Elm Studio has no orders. orders.dtypes lists each column's type:

order_id                int64
customer_id             int64
order_date     datetime64[us]
status                    str
amount                float64
dtype: object

str is text, and datetime64[us] is the timestamp type that pd.to_datetime produced from the date strings. To inspect a table, orders.head(3) returns the first three rows, orders.shape returns (8, 5), orders.info() prints each column's type and non-null count, and orders.describe() returns summary statistics such as the count, mean, and quartiles.

SQL to pandas: the translation table

Each SQL fragment was run on PostgreSQL 16 against the same rows, and each pandas expression on the DataFrames above.

SQLpandas
select order_id, amountorders[["order_id", "amount"]]
where status = 'completed' and amount >= 100orders[(orders["status"] == "completed") & (orders["amount"] >= 100)]
where amount is nullorders[orders["amount"].isna()]
group by status with count(*) and sum(amount)orders.groupby("status").agg(...)
having count(*) > 1by_status[by_status["orders"] > 1]
left join orders using (customer_id)customers.merge(orders, on="customer_id", how="left")
order by amount descorders.sort_values("amount", ascending=False)
limit 3.head(3)
select distinct statusorders["status"].drop_duplicates()
union allpd.concat([orders, orders])
row_number() over (partition by customer_id order by order_date).groupby("customer_id").cumcount() + 1 on sorted rows
sum(amount) over (partition by customer_id).groupby("customer_id")["amount"].transform("sum")
group by date_trunc('month', order_date)orders.resample("MS", on="order_date")

Select, filter, and sort

A comparison on a column returns a Series of True and False values, and passing it inside square brackets keeps the True rows. Combine conditions with & (and), | (or), and ~ (not), each condition in its own parentheses.

big = orders[(orders["status"] == "completed") & (orders["amount"] >= 100)]
print(big[["order_id", "order_date", "amount"]].sort_values("amount", ascending=False))
   order_id order_date  amount
3      1004 2026-03-09   310.0
7      1008 2026-04-03   260.0
4      1005 2026-03-15   220.0
0      1001 2026-03-02   120.0

A list of column names returns a DataFrame, and a single name such as orders["amount"] returns a Series. orders.query("status == 'completed' and amount >= 100") returns the same four rows from a string. .loc[rows, columns] selects by label or condition, and .iloc by integer position.

Handle missing data

pandas marks a missing value as NaN (NaT in a datetime column). isna() finds them, and aggregations skip them.

print(orders["amount"].isna().sum())
print(orders["amount"].sum())
print(len(customers[customers["country"] != "US"]))
1
1044.0
3

One amount is missing, and the sum ignores it. To replace or remove missing values, use fillna(0), ffill() (carry the previous value forward), or dropna(subset=["amount"]). The third number is a trap for SQL users: != is True for a missing value, so Dune Travel counts as a non-US customer. In SQL, country <> 'US' excludes that row and returns 2.

Aggregate with groupby

groupby splits the rows into groups, applies a function to each, and combines the results. In agg, each keyword names an output column and gives the input column and the function.

by_status = orders.groupby("status").agg(
    orders=("order_id", "count"),
    revenue=("amount", "sum"),
    avg_order=("amount", "mean"),
)
print(by_status)
           orders  revenue   avg_order
status
completed       6   1004.0  167.333333
pending         1      0.0         NaN
refunded        1     40.0   40.000000

"count" counts non-missing values, like count(column), and size() counts rows, like count(*). The group keys become the index: call reset_index() to turn status back into a column. HAVING is a filter on this result. pivot_table does the same aggregation with one of the keys spread across columns.

Join tables with merge

merge is the SQL join. how accepts inner (the default), left, right, outer, and cross.

joined = customers.merge(orders, on="customer_id", how="left", validate="one_to_many")
per_customer = joined.groupby("customer_name").agg(
    orders=("order_id", "count"),
    revenue=("amount", "sum"),
)
print(per_customer)
               orders  revenue
customer_name
Acme Retail         3    420.0
Borealis Labs       2    295.5
Cobalt Foods        2    310.0
Dune Travel         1     18.5
Elm Studio          0      0.0

Elm Studio survives the left join with zero orders. validate="one_to_many" raises a MergeError if customer_id repeats in customers, which stops a join from silently multiplying rows. indicator=True adds a _merge column that marks unmatched rows as left_only. One side effect: order_id in joined is now float64, because the default integer type cannot hold the missing value in Elm Studio's row. The join types are covered in the joins guide with diagrams.

Window functions: cumcount, cumsum, shift

A window function computes across related rows without collapsing them. In pandas, sort first, then call a method on the grouped column that returns one value per row.

ranked = orders.sort_values(["customer_id", "order_date"])
by_customer = ranked.groupby("customer_id")
windowed = ranked.assign(
    order_number=by_customer.cumcount() + 1,
    running_total=by_customer["amount"].cumsum(),
    prev_amount=by_customer["amount"].shift(1),
)
print(windowed[["customer_id", "amount", "order_number", "running_total", "prev_amount"]])
   customer_id  amount  order_number  running_total  prev_amount
0            1   120.0             1          120.0          NaN
2            1    40.0             2          160.0        120.0
7            1   260.0             3          420.0         40.0
1            2    75.5             1           75.5          NaN
4            2   220.0             2          295.5         75.5
3            3   310.0             1          310.0          NaN
5            3     NaN             2            NaN        310.0
6            4    18.5             1           18.5          NaN

These are row_number(), a running sum(), and lag(). rank() ranks within the group. The SQL versions are in SQL window functions explained with examples.

Dates and time series

The .dt accessor reads parts of a datetime column: orders["order_date"].dt.month, or .dt.day_name(). resample is a group by on time: give it a frequency and the datetime column.

weekly = orders.resample("W", on="order_date").agg(
    orders=("order_id", "count"),
    revenue=("amount", "sum"),
)
print(weekly)
            orders  revenue
order_date
2026-03-08       3    235.5
2026-03-15       2    530.0
2026-03-22       0      0.0
2026-03-29       1      0.0
2026-04-05       2    278.5

"W" means weeks ending on Sunday, labeled by that Sunday. The week ending 2026-03-22 has no orders and still gets a row, which a SQL GROUP BY would not return. "MS" groups by month start: orders.resample("MS", on="order_date")["amount"].sum() returns 765.5 for March and 278.5 for April. weekly["revenue"].rolling(2).mean() adds a two-week moving average, and weekly["revenue"].plot() draws a line chart with Matplotlib, which is installed separately.

Read and write CSV, JSON, and Parquet

Each format has a pd.read_* function and a to_* method. This writes orders three ways and reads back the type of the date column:

orders.to_csv("orders.csv", index=False)
orders.to_json("orders.jsonl", orient="records", lines=True, date_format="iso")
orders.to_parquet("orders.parquet", index=False)

print(pd.read_csv("orders.csv")["order_date"].dtype)
print(pd.read_json("orders.jsonl", lines=True)["order_date"].dtype)
print(pd.read_parquet("orders.parquet")["order_date"].dtype)
str
str
datetime64[us]
FormatColumn typesOptions to know
CSVInferred on every read. Dates come back as textparse_dates=["order_date"] restores the dates. dtype sets types, usecols limits columns, chunksize reads in pieces
JSON Lines (one object per line)Inferred. The ISO dates came back as textConvert with pd.to_datetime. pd.json_normalize flattens nested API responses into columns such as customer.name
ParquetStored in the file. The frame read back equals the originalcolumns=[...] reads only the columns you name. Needs PyArrow or fastparquet

index=False keeps the row numbers out of the file. pandas also reads Excel with pd.read_excel (install the excel extra) and databases with pd.read_sql(query, connection), and to_sql writes a DataFrame to a table. For files to practice on, see the datasets for Python and pandas practice.

Where pandas and SQL return different answers

These came from running the same rows through PostgreSQL 16 and pandas 3.1.1. None of them raises an error.

CasePostgreSQL 16pandas 3.1.1To match SQL
country <> 'US' with a missing countryRow excluded: 2Row included: 3Add & customers["country"].notna()
Sum of a group with no amounts (pending)NULL0.0.sum(min_count=1)
Group by a column with a missing valueNULL is its own groupRow droppedgroupby("country", dropna=False)
Descending sortNULL firstNaN lastna_position="first"
Running total on the row with no amount310.00NaNfillna(0) before cumsum()
Join keys that are both missingDo not matchMatch each otherdropna(subset=[key]) before merge
Week with no ordersNo rowRow with 0weekly[weekly["orders"] > 0]

When to use pandas and when to stay in SQL

pandas keeps the whole table in memory on one machine, and its documentation says data larger than memory, or even a sizable fraction of it, becomes hard to work with. Our advice: transform warehouse tables in SQL, where the data already is, and use pandas for what SQL does badly, such as files, API responses, small extracts, and one-off analysis. The Python hub lists the next steps, Python basics for analytics engineers covers the language itself, and the SQL hub covers the other side.

Frequently Asked Questions

How can I start learning pandas for data analysis in Python?

Install pandas, build a small DataFrame by hand as this page does, and translate queries you can already write in SQL: a filter, a GROUP BY, a join. Check each result against the SQL answer, then move to real files with pd.read_csv.

How do you handle missing data in a pandas DataFrame?

Find it with isna(), and count it per column with df.isna().sum(). Then choose: dropna() removes rows, fillna(value) replaces missing values, and ffill() or bfill() copies a neighboring value. Sums and means skip missing values by default.

How do you merge and join DataFrames in pandas?

Use left.merge(right, on="key", how="left"). how sets the join type, and left_on and right_on handle keys with different names. Pass validate to fail on duplicate keys. pd.concat stacks DataFrames with the same columns, like UNION ALL.

How do you optimize pandas performance for large datasets?

The pandas documentation recommends loading less data (usecols for CSV, columns for Parquet), using efficient types such as category for text with few distinct values, and processing in chunks with chunksize. Beyond that, it points to other libraries.

Why does code from older pandas tutorials fail on pandas 3?

pandas 3.0 changed three things that older examples rely on. Text columns are str, not object. fillna(method="ffill") raises a TypeError: call ffill(). And chained assignment such as df[mask]["amount"] = 0 no longer changes df: write df.loc[mask, "amount"] = 0.

Primary sources and further reading

The Python code was run on pandas 3.1.1 with PyArrow 26.0.1 and Python 3.11, and the output shown is what it printed. The SQL comparisons were run on PostgreSQL 16. The sources are pages of the pandas 3.1.1 documentation, read in November 2026.