Skip to content

/cheatsheets/pandas/pandas-cheat-sheet

pandas cheat sheet: read, select, filter, group and reshape

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated 2026-10-20
tool
pandas
versions
pandas 3.x
os
any

The pandas operations you use every day, run on one small DataFrame with pandas 3.

bash
python -c '
import pandas as pd
df = pd.DataFrame({
    "city": ["Rome", "Milan", "Rome", "Turin", "Milan"],
    "month": ["jan", "jan", "feb", "feb", "feb"],
    "sales": [120, 80, 150, 60, 95],
})
print("--- filter and sort");     print(df[df["sales"] > 90].sort_values("sales", ascending=False).to_string(index=False))
print("--- group and aggregate"); print(df.groupby("city")["sales"].agg(["sum", "mean"]).to_string())
print("--- pivot");               print(df.pivot_table(index="city", columns="month", values="sales", aggfunc="sum").to_string())
print("--- new column");          print(df.assign(share=(df["sales"] / df["sales"].sum()).round(2)).head(2).to_string(index=False))'

Output

--- filter and sort
 city month  sales
 Rome   feb    150
 Rome   jan    120
Milan   feb     95
--- group and aggregate
       sum   mean
city
Milan  175   87.5
Rome   270  135.0
Turin   60   60.0
--- pivot
month    feb    jan
city
Milan   95.0   80.0
Rome   150.0  120.0
Turin   60.0    NaN
--- new column
 city month  sales  share
 Rome   jan    120   0.24
Milan   jan     80   0.16

Read and write

TaskCode
CSVpd.read_csv("f.csv", dtype={"id": "str"}, parse_dates=["ts"])
Excelpd.read_excel("f.xlsx", sheet_name="Sheet1")
Parquetpd.read_parquet("f.parquet")
SQLpd.read_sql("SELECT * FROM t", engine)
Writedf.to_csv("out.csv", index=False) / df.to_parquet("out.parquet")

Inspect

TaskCode
First rowsdf.head(10)
Types and nullsdf.info()
Statisticsdf.describe()
Count valuesdf["col"].value_counts()
Shapedf.shape

Select and filter

TaskCode
Columnsdf[["a", "b"]]
Rows by labeldf.loc[df["a"] > 0, ["a", "b"]]
Rows by positiondf.iloc[0:5, 0:2]
Several conditionsdf[(df.a > 0) & (df.b == "x")]
In a listdf[df["city"].isin(["Rome", "Milan"])]
Text matchdf[df["name"].str.contains("abc", na=False)]

Clean and transform

TaskCode
Missing valuesdf.dropna() / df.fillna({"a": 0})
Renamedf.rename(columns={"old": "new"})
Change typedf["a"].astype("int64") / pd.to_datetime(df["ts"])
Remove duplicatesdf.drop_duplicates(subset=["id"])
Apply a functiondf["a"].map(f) (prefer vectorised operations)

Sources