Data Science Cheat Sheets: Code, Formulas and Commands ๐Ÿ“

Resources
Cheat Sheets
Reference
One-page references for pandas, NumPy, SQL, statistics, ML metrics, scikit-learn, Git and Docker, plus an interactive metrics calculator, a distribution explorer, a test chooser and the best external cheat sheets.
Author

MLStation

Published

October 1, 2026

Keep this page open in a tab while you work. Every block has a copy button ๐Ÿ“‹, formulas are written out in full, and the interactive tools answer the questions people search for most: โ€œWhich metric?โ€, โ€œWhich distribution?โ€, โ€œWhich test?โ€.

Tip๐ŸŽฏ What is inside
  • ๐Ÿ Code cheat sheets: pandas, NumPy, SQL, scikit-learn, plotting, Git, Docker
  • ๐Ÿงฎ Formula sheets: statistics and ML metrics
  • ๐ŸŽ›๏ธ Three interactive tools: metrics calculator, distribution explorer, test chooser
  • ๐Ÿ”— The best free external cheat sheets, with what each is good for
Note๐Ÿ“š The Resources hub

๐Ÿ Code cheat sheets

import pandas as pd
df = pd.read_csv("sales.csv", parse_dates=["date"])

df.head(); df.info(); df.describe()       # first look
df["region"].value_counts()               # category counts
df.isna().mean()                          # share missing per column

df[df.amount > 100]                       # filter rows
df.query("amount > 100 and region == 'TX'")
df.loc[:, ["date", "amount"]]             # select columns

df["month"] = df.date.dt.to_period("M")   # new column
df.groupby("region").amount.agg(["sum", "mean", "count"])
df.pivot_table(index="month", columns="region",
               values="amount", aggfunc="sum")

df.merge(customers, on="customer_id", how="left")
df.sort_values("amount", ascending=False)
df.fillna({"amount": 0}).drop_duplicates()
df.to_parquet("sales.parquet")            # fast, typed storage
import numpy as np
a = np.array([[1, 2], [3, 4]])
a.shape, a.dtype, a.T                      # shape, type, transpose
np.zeros((3, 4)); np.ones(5); np.arange(0, 10, 2)
np.linspace(0, 1, 5)                       # 5 evenly spaced values

a.sum(axis=0); a.mean(axis=1); a.max()     # reductions
a @ a                                      # matrix multiply
np.where(a > 2, 1, 0)                      # vectorised if-else
a[a > 2]                                   # boolean mask

rng = np.random.default_rng(42)            # reproducible random
rng.normal(0, 1, 1000); rng.integers(0, 10, 5)
np.percentile(x, [5, 50, 95])
-- top 5 regions by revenue in 2026
SELECT region,
       SUM(amount)        AS revenue,
       COUNT(*)           AS orders,
       AVG(amount)        AS avg_order
FROM   sales
WHERE  order_date >= '2026-01-01'
GROUP  BY region
HAVING COUNT(*) > 100
ORDER  BY revenue DESC
LIMIT  5;

-- join + window function: each order's share of its region
SELECT s.order_id, c.segment, s.amount,
       s.amount / SUM(s.amount) OVER (PARTITION BY s.region)
         AS share_of_region
FROM   sales s
LEFT   JOIN customers c ON c.id = s.customer_id;
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import HistGradientBoostingClassifier

prep = make_column_transformer(
    (StandardScaler(), ["age", "income"]),
    (OneHotEncoder(handle_unknown="ignore"), ["plan"]))
model = make_pipeline(prep, HistGradientBoostingClassifier())

Xtr, Xte, ytr, yte = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=0)
cross_val_score(model, Xtr, ytr, cv=5, scoring="roc_auc")
model.fit(Xtr, ytr)
proba = model.predict_proba(Xte)[:, 1]
import plotly.express as px
px.histogram(df, x="amount", nbins=50)
px.scatter(df, x="income", y="spend", color="segment",
           trendline="ols")
px.line(daily, x="date", y="revenue", color="region")
px.box(df, x="region", y="amount")

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(daily.date, daily.revenue, lw=2)
ax.set(title="Daily revenue", xlabel="", ylabel="$")
fig.tight_layout(); fig.savefig("revenue.png", dpi=200)
git clone <url>                 # copy a repository
git status                      # what changed?
git switch -c feature/churn     # new branch
git add notebook.ipynb src/     # stage changes
git commit -m "Add churn baseline"
git pull --rebase               # get others' work
git push -u origin feature/churn
git log --oneline --graph -10   # recent history
git restore file.py             # discard local edits
docker build -t myapi:1.0 .            # build image
docker run -d -p 8000:8000 myapi:1.0   # run container
docker ps                              # running containers
docker logs -f <id>                    # follow logs
docker exec -it <id> sh                # shell inside
docker compose up -d                   # multi-container app
docker system prune                    # free disk space

๐Ÿงฎ Statistics formula sheet

Table 1: Statistics formulas
Concept Formula Plain words
Mean \bar x = \frac{1}{n}\sum_{i=1}^n x_i The balance point
Sample variance s^2 = \frac{1}{n-1}\sum (x_i - \bar x)^2 Average squared distance from the mean
Standard error \text{SE} = s/\sqrt{n} How much the mean wobbles between samples
z-score z = (x - \mu)/\sigma How many standard deviations from the mean
95% CI for a mean \bar x \pm 1.96\,\text{SE} Plausible range for the true mean
Correlation r = \frac{\text{cov}(x,y)}{s_x s_y} Strength of a straight-line relationship
Bayesโ€™ rule P(A\mid B) = \frac{P(B\mid A)P(A)}{P(B)} Update a belief with evidence
Linear regression \hat\beta = (X^\top X)^{-1}X^\top y Best-fit coefficients

๐Ÿ“ ML metrics formula sheet

Table 2: ML metrics
Metric Formula Use when
Accuracy \frac{TP+TN}{TP+TN+FP+FN} Classes are balanced
Precision \frac{TP}{TP+FP} False alarms are costly
Recall \frac{TP}{TP+FN} Misses are costly
F1 2\cdot\frac{P\cdot R}{P+R} You need one balanced number
MAE \frac{1}{n}\sum\lvert y-\hat y\rvert Errors in the targetโ€™s units
RMSE \sqrt{\frac{1}{n}\sum (y-\hat y)^2} Large errors matter more
MAPE \frac{100}{n}\sum\left\lvert\frac{y-\hat y}{y}\right\rvert Percent error (avoid when y \approx 0)
R^2 1 - \frac{\sum (y-\hat y)^2}{\sum (y-\bar y)^2} Share of variance explained
Log loss -\frac{1}{n}\sum [y\ln p + (1-y)\ln(1-p)] Probabilities must be well calibrated

๐ŸŽ›๏ธ Tool 1: metrics calculator

A model scores 1,000 simulated cases, 15% of which are positive. Move the threshold and watch the confusion matrix and every metric update.

Notice that accuracy stays high even at bad thresholds, because 85% of cases are negative. That is why precision and recall exist.

๐ŸŽ›๏ธ Tool 2: distribution explorer

๐ŸŽ›๏ธ Tool 3: which statistical test?

flowchart TD
  A["โ“ What are you comparing?"] --> B["Means of a numeric variable"]
  A --> C["Proportions or counts"]
  A --> D["Relationship between two numeric variables"]
  B --> B1{"How many groups?"}
  B1 -- "2" --> B2{"Same subjects twice?"}
  B2 -- yes --> T1["Paired t-test<br/>or Wilcoxon signed-rank"]
  B2 -- no --> T2["Welch t-test<br/>or Mann-Whitney U"]
  B1 -- "3+" --> T3["ANOVA<br/>or Kruskal-Wallis"]
  C --> C1{"Table size"}
  C1 -- "2 groups, yes/no" --> T4["Two-proportion z-test<br/>or Fisher exact"]
  C1 -- "larger table" --> T5["Chi-square test"]
  D --> T6["Pearson r, or Spearman<br/>if not linear"]

The second option in each box is the non-parametric version, safer when data are skewed or small. See our p-value explainer for what the result means.

๐Ÿ”— The best external cheat sheets

Table 3: External cheat sheets
Cheat sheet Covers Why it is useful
pandas official cheat sheet (PDF) Reshaping, subsetting, grouping, merging Visual diagrams of how tables change shape
Stanford CS229 cheat sheets (GitHub) Supervised, unsupervised, deep learning, probability, linear algebra Dense, beautifully illustrated theory refreshers
scikit-learn โ€œchoosing the right estimatorโ€ Which algorithm to try for your data Interactive flowchart, downloadable as SVG
Matplotlib cheat sheets and handouts Plot types, colours, layout tips Beginner, intermediate and tips handouts
Posit cheat sheets R, tidyverse, Shiny, Quarto, some Python The classic two-page cheat sheet format
DataCamp cheat sheets Python, SQL, Power BI, ML, AI tools Broad directory across data topics
GitHub Git cheat sheet (PDF) Everyday Git commands One page, printable
Docker CLI cheat sheet (PDF) Images, containers, registries Official commands reference
Note๐Ÿ“ Note

Cheat sheets are for recall, not learning. If a line on a sheet makes no sense, read the matching section of the docs or our articles first, then come back.

๐Ÿงฉ Summary

  • Bookmark this page: ๐Ÿ code, ๐Ÿงฎ formulas and ๐ŸŽ›๏ธ interactive tools in one place.
  • Use the metrics calculator to see why accuracy misleads on imbalanced data.
  • Use the test chooser before running any hypothesis test.
  • For depth, the CS229, pandas and scikit-learn sheets are the best free companions.
  • Next: look up any unfamiliar word in the glossary ๐Ÿ“–.
Back to top