Code Reference

Pandas

Python · Reference cheat sheet

Pandas

Python · Reference cheat sheet


📋 Overview

Pandas is the go-to tabular data library. Install with pip install pandas. Core types: Series (1D labeled) and DataFrame (2D table). Typical flow: read_csv → filter/transform → groupby / mergeto_csv.

🔧 Core concepts

APIRole
pd.Series(data)1D labeled array
pd.DataFrame(data)Table (columns + index)
pd.read_csv(path)Load CSV
df[mask] / .loc / .ilocFilter / select
df.groupby(col)Split-apply-combine
pd.merge(left, right, on=...)Join tables
df.to_csv(path, index=False)Export
df.head() / .info() / .describe()Inspect

💡 Examples

Read and filter:

import pandas as pd

df = pd.read_csv("sales.csv")
active = df[df["status"] == "active"]
big = df.loc[df["amount"] > 100, ["name", "amount"]]
print(df.head(), active.shape)

Groupby:

import pandas as pd

df = pd.read_csv("orders.csv")
summary = (
    df.groupby("region", as_index=False)["amount"]
    .sum()
    .sort_values("amount", ascending=False)
)
print(summary)

Merge:

import pandas as pd

orders = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
joined = pd.merge(orders, customers, on="customer_id", how="left")
print(joined.head())

Write CSV:

import pandas as pd

df = pd.DataFrame({"a": [1, 2], "b": ["x", "y"]})
df.to_csv("out.csv", index=False, encoding="utf-8")

⚠️ Pitfalls

  • Install first: pip install pandas (not in the stdlib).
  • Chained indexing (df[...][...] =) can fail silently — prefer .loc.
  • groupby default may leave the key as index; use as_index=False when you want a flat frame.
  • Merges duplicate key columns as _x / _y if names collide — set suffixes.
  • Large CSVs: pass usecols, dtype, or chunk with chunksize=.

On this page