Pandas Cheat Sheet
Free Pandas cheat sheet: the most-used Pandas syntax and methods at a glance — searchable and beginner-friendly.
Creating & Loading
| Concept | Syntax | Example |
|---|---|---|
| Import pandas The universal alias — every snippet assumes pd. | import pandas as pd | import pandas as pd |
| DataFrame from dict Keys become column names, lists become rows. | pd.DataFrame({"col": [...]}) | df = pd.DataFrame({"name": ["Ada", "Bob"], "age": [36, 28]}) |
| Series A single labeled column — one of these per DataFrame column. | pd.Series([...]) | s = pd.Series([1, 2, 3], name="nums") |
| Read CSV Use index_col=, usecols=, parse_dates= to control parsing. | pd.read_csv("file.csv") | df = pd.read_csv("data.csv") |
| Read Excel / JSON read_excel needs openpyxl installed. | pd.read_excel(...) / pd.read_json(...) | df = pd.read_excel("book.xlsx", sheet_name="Sheet1") |
| Write CSV index=False avoids writing the row numbers as a column. | df.to_csv("out.csv", index=False) | df.to_csv("clean.csv", index=False) |
Inspecting
| Concept | Syntax | Example |
|---|---|---|
| First / last rows Defaults to 5 rows. Great for a quick peek. | df.head(n) / df.tail(n) | df.head() # first 5 rows |
| Shape A tuple — df.shape[0] is the row count. | df.shape | df.shape # (rows, columns) |
| Column info Shows dtypes, non-null counts and memory use. | df.info() | df.info() |
| Summary stats count, mean, std, min, quartiles, max for numeric columns. | df.describe() | df.describe() |
| Column names / dtypes df.dtypes shows the type of each column. | df.columns / df.dtypes | list(df.columns) |
| Unique / value counts df["col"].unique() returns the distinct values. | df["col"].value_counts() | df["city"].value_counts() |
Selecting & Filtering
| Concept | Syntax | Example |
|---|---|---|
| Select column Returns a Series. df[["a", "b"]] returns a DataFrame. | df["col"] | df["age"] |
| Label-based access loc is inclusive of the end label. | df.loc[rows, cols] | df.loc[0:5, ["name", "age"]] |
| Position-based access iloc uses integer positions, end-exclusive like Python slices. | df.iloc[rows, cols] | df.iloc[0:5, 0:2] |
| Boolean filter Build a mask, then index with it. | df[df["col"] > x] | df[df["age"] > 30] |
| Combine conditions Use & | ~ with parentheses, NOT and/or. | df[(cond1) & (cond2)] | df[(df["age"] > 30) & (df["city"] == "NYC")] |
| Query Readable string filtering — handy for complex conditions. | df.query("expr") | df.query("age > 30 and city == 'NYC'") |
Cleaning & Missing Data
| Concept | Syntax | Example |
|---|---|---|
| Find nulls Counts missing values per column. | df.isnull().sum() | df.isnull().sum() |
| Drop missing axis=1 drops columns; subset= limits which columns count. | df.dropna() | df.dropna(subset=["age"]) |
| Fill missing Fill with a constant, mean, median, or method="ffill". | df.fillna(value) | df["age"] = df["age"].fillna(df["age"].mean()) |
| Drop duplicates Keeps the first occurrence by default. | df.drop_duplicates() | df.drop_duplicates(subset=["email"]) |
| Rename columns Pass inplace=True or reassign df. | df.rename(columns={...}) | df.rename(columns={"old": "new"}) |
| Convert dtype pd.to_datetime() and pd.to_numeric() handle tricky conversions. | df["col"].astype(type) | df["age"] = df["age"].astype(int) |
Transforming
| Concept | Syntax | Example |
|---|---|---|
| New / derived column Vectorized math runs across the whole column. | df["new"] = expr | df["bonus"] = df["salary"] * 0.1 |
| Apply a function Use a lambda for inline logic: apply(lambda x: x + 1). | df["col"].apply(func) | df["name"] = df["name"].apply(str.upper) |
| Map values Map with a dict or function for element-wise replacement. | df["col"].map(mapping) | df["grade"] = df["score"].map({90: "A", 80: "B"}) |
| Sort Pass a list to sort by multiple columns. | df.sort_values("col") | df.sort_values("age", ascending=False) |
| String methods The .str accessor exposes Python string methods vectorized. | df["col"].str.method() | df["email"].str.lower().str.strip() |
| Bin into categories Turns a numeric column into labeled ranges. | pd.cut(series, bins) | pd.cut(df["age"], bins=[0, 18, 65, 120], labels=["minor", "adult", "senior"]) |
Grouping & Aggregation
| Concept | Syntax | Example |
|---|---|---|
| Group by Split-apply-combine: group, then aggregate. | df.groupby("col") | df.groupby("city")["salary"].mean() |
| Multiple aggregations Different functions per column in one call. | df.groupby(c).agg({...}) | df.groupby("dept").agg({"salary": ["mean", "max"], "id": "count"}) |
| Count per group size() counts rows including NaN; count() excludes NaN. | df.groupby(c).size() | df.groupby("city").size() |
| Pivot table Spreadsheet-style cross-tabulation. | df.pivot_table(...) | df.pivot_table(values="sales", index="region", columns="month", aggfunc="sum") |
| Reset index Turns a grouped index back into a normal column. | df.reset_index() | df.groupby("city").mean().reset_index() |
Merging & Reshaping
| Concept | Syntax | Example |
|---|---|---|
| Merge / join how can be inner, left, right, or outer. | pd.merge(a, b, on="key") | pd.merge(orders, users, on="user_id", how="left") |
| Concatenate Stack rows (axis=0) or columns (axis=1). | pd.concat([a, b]) | pd.concat([jan, feb], ignore_index=True) |
| Melt (wide to long) Unpivots columns into rows. | df.melt(id_vars=[...]) | df.melt(id_vars=["name"], var_name="month", value_name="sales") |
| Pivot (long to wide) The inverse of melt. | df.pivot(index, columns, values) | df.pivot(index="name", columns="month", values="sales") |
| Set / multi index Pass a list for a hierarchical (MultiIndex) layout. | df.set_index("col") | df.set_index(["region", "city"]) |