Data Science Cheat Sheet: Python, Stats & ML Quick Reference

Thirty seconds into a technical interview, you blank on the syntax for groupby().agg(). Or you're mid-project and can't remember whether to use RMSE or MAE for your regression output. This data science cheat sheet exists for those moments — a single-page reference covering the code, formulas, and decision rules you'll reach for most often.

This isn't a beginner tutorial. It assumes you know what a DataFrame is. It's structured so you can scan a section in under a minute and get back to work.

Python & Pandas Data Science Cheat Sheet

Pandas is the workhorse of most data science workflows. These are the operations that come up on nearly every project.

Loading & Inspecting Data

import pandas as pd
import numpy as np

df = pd.read_csv('data.csv')
df.head(10)          # first 10 rows
df.info()            # dtypes + null counts
df.describe()        # stats for numeric cols
df.shape             # (rows, cols)
df.dtypes
df.isnull().sum()    # nulls per column
df.nunique()         # unique values per column

Selecting & Filtering

# Column selection
df[['col1', 'col2']]
df.loc[df['col'] > 5, ['col', 'col2']]   # label-based
df.iloc[0:5, 1:3]                         # position-based

# Filtering
df[df['salary'] > 80000]
df.query("salary > 80000 and role == 'analyst'")

Transforming Data

# Aggregation
df.groupby('department')['salary'].agg(['mean', 'median', 'count'])

# Apply custom function
df['col'].apply(lambda x: x * 1.1)

# Pivot
df.pivot_table(values='sales', index='region', columns='year', aggfunc='sum')

# Merge
pd.merge(df1, df2, on='id', how='left')

# Handling nulls
df.fillna(0)
df.dropna(subset=['critical_col'])
df['col'].fillna(df['col'].median())

Common String Operations

df['name'].str.lower()
df['name'].str.contains('Smith', na=False)
df['name'].str.replace(' ', '_')
df['text'].str.split(',').str[0]

Statistics Cheat Sheet for Data Science

You don't need to memorize derivations. You do need to know which formula applies when, and what the output actually means.

Descriptive Stats

  • Mean: sensitive to outliers. Use for symmetric distributions.
  • Median: robust to outliers. Use for skewed distributions (income, house prices).
  • Standard deviation (σ): average distance from the mean. Low σ = tight cluster.
  • IQR: Q3 − Q1. Standard outlier rule: flag values outside [Q1 − 1.5×IQR, Q3 + 1.5×IQR].

Probability Distributions You Actually Encounter

  • Normal (Gaussian): heights, measurement errors, residuals in linear regression
  • Binomial: yes/no outcomes repeated N times (conversion rates, defects per batch)
  • Poisson: count of events in a fixed interval (support tickets per hour, clicks per day)
  • Exponential: time between events (time between failures, inter-arrival times)

Hypothesis Testing Quick Reference

  • t-test: compare means of 1 or 2 groups. Assumes normality. Use Welch's variant if variances differ.
  • Chi-squared: test independence between two categorical variables (e.g., A/B test conversion by device)
  • ANOVA: compare means across 3+ groups. Follow up with Tukey HSD for pairwise comparison.
  • Mann-Whitney U: non-parametric alternative to t-test when normality fails

p-value rule: p < 0.05 means the result is statistically significant at the 5% level — not that the effect is meaningful. Always pair with effect size (Cohen's d, odds ratio).

Correlation vs. Causation

  • Pearson r: linear relationship between two continuous variables. Range −1 to 1.
  • Spearman ρ: rank-based, handles non-linear monotonic relationships and ordinal data.
  • Correlation above 0.7 in your feature set = multicollinearity risk. Check VIF before running regression.

Machine Learning Algorithm Cheat Sheet

Picking the wrong algorithm wastes days. This decision map covers the most common scenarios.

Supervised Learning

  • Linear Regression: continuous target, linear relationship, few features. Baseline for regression tasks.
  • Logistic Regression: binary classification baseline. Interpretable coefficients = stakeholder-friendly. Use before reaching for XGBoost.
  • Random Forest: handles mixed types, non-linear relationships, missing-value-tolerant. Good default when you don't know what's going on in the data.
  • XGBoost / LightGBM: tabular data gold standard in competitions. Tune max_depth, learning_rate, n_estimators first.
  • SVM: high-dimensional text or image classification. Slow on large datasets; rarely used when tree ensembles are available.
  • k-NN: lazy learner, no training phase. Slow at inference. Useful for recommendation prototypes.

Unsupervised Learning

  • K-Means: fast clustering. Requires you to specify k. Fails on non-spherical clusters.
  • DBSCAN: finds arbitrary-shaped clusters + noise/outliers. No k required. Sensitive to epsilon and min_samples.
  • PCA: dimensionality reduction. Use before visualization (t-SNE) or when features are correlated. Loses interpretability.
  • t-SNE / UMAP: 2D/3D visualization of high-dimensional data. Not for preprocessing pipelines — only for EDA.

Evaluation Metrics at a Glance

  • Classification: Accuracy (balanced classes), F1 (imbalanced), ROC-AUC (ranking quality), Precision/Recall tradeoff.
  • Regression: MAE (interpretable, same units), RMSE (penalizes large errors more heavily), R² (proportion of variance explained).
  • When classes are imbalanced: ditch accuracy. Use F1, PR-AUC, or set class weights.

SQL Data Science Cheat Sheet

SQL is the one skill that separates data scientists who can get their own data from those who have to wait for data engineers. These patterns cover 90% of analyst-level queries.

-- Window functions (most useful for data science)
SELECT
  user_id,
  event_date,
  revenue,
  SUM(revenue) OVER (PARTITION BY user_id ORDER BY event_date) AS running_total,
  LAG(revenue, 1) OVER (PARTITION BY user_id ORDER BY event_date) AS prev_revenue,
  RANK() OVER (PARTITION BY cohort ORDER BY revenue DESC) AS rank_in_cohort
FROM events;

-- Cohort retention
SELECT
  DATE_TRUNC('month', first_purchase) AS cohort_month,
  DATE_TRUNC('month', event_date) AS activity_month,
  COUNT(DISTINCT user_id) AS active_users
FROM user_activity
GROUP BY 1, 2;

-- Finding duplicates
SELECT email, COUNT(*) as cnt
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

-- Percent of total
SELECT
  category,
  revenue,
  revenue * 100.0 / SUM(revenue) OVER () AS pct_of_total
FROM sales;

If you're working with large-scale data (billions of rows), the SQL dialect shifts toward BigQuery, Snowflake, or Spark SQL, but the window function patterns above translate directly.

Top Courses to Go Deeper

A cheat sheet gets you unstuck; structured courses fill the gaps. These are the highest-rated options for building real data science depth, not just syntax familiarity.

Introduction to Data Analytics (Coursera)

Rated 9.8/10 across thousands of learners. Covers the full analytics workflow — data cleaning, visualization, and interpretation — with hands-on projects that give you portfolio evidence, not just certificate PDFs.

Tools for Data Science (Coursera)

Rated 9.8/10. Focuses specifically on the toolchain: Jupyter, RStudio, GitHub, Watson Studio. If you've been winging your environment setup, this course standardizes it fast.

Python for Data Science, AI & Development by IBM (Coursera)

Rated 9.8/10. The IBM Data Science certificate is one of the most employer-recognized credentials on LinkedIn. This course is the Python foundation module — covers Pandas, NumPy, and APIs in a job-context framing, not academic theory.

Analyze Data to Answer Questions (Coursera)

Rated 9.8/10. Part of the Google Data Analytics certificate. Teaches the analytical thinking framework alongside SQL and spreadsheet skills — useful if you're bridging into data from a non-technical background.

Process Data from Dirty to Clean (Coursera)

Rated 9.8/10. Data cleaning eats 60–80% of real project time. This course treats it as a first-class skill rather than a footnote, which is the right call.

Python Data Science (EDX)

Rated 9.7/10. A solid alternative to the Coursera stack, particularly if you prefer self-paced learning without weekly deadlines. Covers statistical thinking alongside Python implementation.

FAQ

What should a data science cheat sheet include?

At minimum: key Pandas and NumPy operations, statistical test decision rules, ML algorithm selection criteria, evaluation metrics for classification and regression, and SQL window functions. Anything you look up more than twice a week belongs on it.

Is there one cheat sheet that covers everything?

No, and be skeptical of any that claims to. A good cheat sheet covers one domain deeply — Pandas syntax, or statistics, or SQL. Trying to cover everything produces a wall of text that's useless in practice. Bookmark 3-4 focused references rather than one giant one.

Do data science interviews test cheat sheet knowledge?

Technical screens test whether you understand the concepts, not whether you can write perfect syntax from memory. Interviewers care more about whether you know when to use a Mann-Whitney test vs a t-test, or why RMSE penalizes outliers more than MAE, than whether you remember the exact Pandas method signature. The thinking matters more than recall.

How is a data science cheat sheet different from a machine learning cheat sheet?

Data science cheat sheets typically cover the full workflow: data ingestion, cleaning, EDA, statistics, and model evaluation. ML cheat sheets narrow in on algorithm selection, hyperparameter ranges, and model comparison. The overlap is in evaluation metrics and feature engineering — both cover those.

Which Python libraries do I need for data science?

The practical core: Pandas (data manipulation), NumPy (numerical ops), Matplotlib/Seaborn (visualization), Scikit-learn (ML), Statsmodels (statistical tests). For deep learning, add PyTorch or TensorFlow. For big data, PySpark. Most jobs require only the first five.

Should I memorize all of this?

No. The goal is familiarity, not memorization. If you've used a method a few times, your brain will encode the pattern — you'll remember that groupby + agg is how you aggregate, even if you need to look up the exact syntax. Focus on understanding what each function does, not on rote recall.

Bottom Line

This data science cheat sheet is a reference, not a curriculum. Use the Python section when you're in the middle of EDA and blanking on syntax. Use the statistics section when you're deciding which test applies to your data. Use the ML section when you're scoping a modeling approach and need to justify your choice to a stakeholder.

If you find yourself looking up the same concept repeatedly, that's the signal to go deeper — a structured course will get you to the point where the pattern is internalized, not just looked up. The Coursera and EDX options above are the highest-rated starting points for building that depth without wading through low-quality material.

Save this page. Come back when you're stuck.

Looking for the best course? Start here:

Related Articles

More in this category

Course AI Assistant Beta

Hi! I can help you find the perfect online course. Ask me something like “best Python course for beginners” or “compare data science courses”.