pandas has hundreds of methods. Your daily work uses about 10.
Part 1 is those 10. Part 2 answers the 21 questions you end up Googling: filter with two conditions, top 3 per group, rank, month-on-month change.
Save it. Code daily.
Top 10 methods
- 01
read_csv
df = pd.read_csv("sales.csv") - 02
info
df.info() - 03
Filter rows
df[df["amount"] > 500] - 04
loc
df.loc[df["city"] == "Pune", ["name", "amount"]] - 05
groupby
df.groupby("city")["amount"].sum() - 06
sort_values
df.sort_values("amount", ascending=False) - 07
merge
pd.merge(orders, users, on="user_id", how="left") - 08
fillna
df["amount"].fillna(0) - 09
drop_duplicates
df.drop_duplicates(subset="email") - 10
value_counts
df["city"].value_counts()
pandas: how do I …
- 01
Count rows and columns
df.shape - 02
See column types
df.dtypes - 03
Count missing values per column
df.isna().sum() - 04
Rename a column
df.rename(columns={"amt": "amount"}) - 05
Drop a column
df.drop(columns="notes") - 06
Convert text to a date
pd.to_datetime(df["date"]) - 07
Pull the month from a date
df["date"].dt.month - 08
Filter with two conditions
df[(df.city == "Pune") & (df.amount > 500)] - 09
Match a list of values
df[df["city"].isin(["Pune", "Indore"])] - 10
Search text in a column
df[df["name"].str.contains("kumar", case=False)] - 11
Count unique customers
df["customer_id"].nunique() - 12
Sum and mean per group
df.groupby("city")["amount"].agg(["sum", "mean"]) - 13
Excel-style pivot
df.pivot_table(index="city", columns="month", values="amount", aggfunc="sum") - 14
Top 3 rows per city
(df.sort_values("amount", ascending=False) .groupby("city").head(3)) - 15
Rank inside each group
df.groupby("dept")["salary"].rank(ascending=False) - 16
Previous row's value
df["sales"].shift(1) - 17
Month-on-month % change
df["sales"].pct_change() - 18
Running total
df["amount"].cumsum() - 19
New column from a condition
np.where(df["amount"] > 1000, "High", "Low") - 20
Stack two tables
pd.concat([df1, df2]) - 21
Save to Excel
df.to_excel("out.xlsx", index=False)
Two imports cover all of this: import pandas as pd and import numpy as np.
Free PDF
pandas cheat sheet: 10 methods + 21 answers
Download the PDFOpens in Google Drive. No sign-up.