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 / merge → to_csv.
🔧 Core concepts
| API | Role |
|---|---|
pd.Series(data) | 1D labeled array |
pd.DataFrame(data) | Table (columns + index) |
pd.read_csv(path) | Load CSV |
df[mask] / .loc / .iloc | Filter / 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. groupbydefault may leave the key as index; useas_index=Falsewhen you want a flat frame.- Merges duplicate key columns as
_x/_yif names collide — setsuffixes. - Large CSVs: pass
usecols,dtype, or chunk withchunksize=.