Master Data Science Cheat Sheet: NumPy, Pandas, SQL & ML Reference

Keep this high-density syntax cheat sheet bookmarked. It provides instantaneous code snippets for the most common data science operations across NumPy, Pandas, Polars, SQL, and Scikit-Learn.

1. NumPy & Linear Algebra Quick Reference

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
mat = np.array([[1, 2], [3, 4]])

# Summary Statistics
mean_val = np.mean(arr)
std_dev  = np.std(arr, ddof=1)          # Sample standard deviation (n-1)
median   = np.median(arr)
p25, p75 = np.percentile(arr, [25, 75]) # Quartiles for IQR

# Linear Algebra Routines
dot_prod = np.dot(u, v)                 # Or u @ v
norm_l2  = np.linalg.norm(v)            # Euclidean norm
inv_mat  = np.linalg.inv(mat)           # Matrix inverse
eig_vals, eig_vecs = np.linalg.eig(mat) # Eigendecomposition
u, s, vt = np.linalg.svd(mat)           # Singular Value Decomposition

2. Pandas vs. Polars Syntax Matrix

Operation Pandas 2.x Syntax Polars High-Speed Syntax
Read Parquet pd.read_parquet("file.parquet") pl.read_parquet("file.parquet")
Filter Rows df[df['age'] > 25] or df.query("age > 25") df.filter(pl.col("age") > 25)
Select / Mutate df['tax'] = df['spend'] * 0.10 df.with_columns((pl.col("spend") * 0.10).alias("tax"))
GroupBy Agg df.groupby('dept')['salary'].mean() df.group_by("dept").agg(pl.col("salary").mean())
Sort Values df.sort_values(by='rev', ascending=False) df.sort("rev", descending=True)
Drop Nulls df.dropna(subset=['email']) df.drop_nulls(subset=["email"])

3. SQL Window Functions & Aggregations

-- Row numbering without ties
ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC)

-- Rank with ties (1, 1, 3)
RANK() OVER (PARTITION BY category ORDER BY sales DESC)

-- Dense rank with ties (1, 1, 2)
DENSE_RANK() OVER (PARTITION BY category ORDER BY sales DESC)

-- Access prior row (Month-over-Month calculation)
LAG(monthly_sales, 1) OVER (PARTITION BY user_id ORDER BY order_month)

-- 7-Day Moving Average frame
AVG(daily_spend) OVER (ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)

4. Scikit-Learn Pipeline & Modeling Reference

from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.model_selection import StratifiedKFold, cross_val_score
from xgboost import XGBClassifier

preprocessor = ColumnTransformer([
    ('num', StandardScaler(), ['age', 'income']),
    ('cat', OneHotEncoder(drop='first'), ['country'])
])

pipe = Pipeline([
    ('prep', preprocessor),
    ('model', XGBClassifier(n_estimators=100, max_depth=4))
])

# Evaluate with Stratified 5-Fold Cross-Validation
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X, y, cv=cv, scoring='roc_auc')

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What makes this Data Science cheat sheet essential?

It consolidates the top 5% of syntax commands used 95% of the time across NumPy, Pandas, Polars, SQL, Scikit-learn, and Plotly into a single, printable quick-reference guide.

Q2. How should I use this cheat sheet during coding?

Bookmark this page or print it out. Use it to quickly look up parameter arguments, syntax patterns (like .loc slicing, SQL window frame clauses, or ColumnTransformer declarations), and avoid frequent syntax lookups on search engines.

Q3. Is Polars included on this cheat sheet?

Yes. Core Polars expressions (pl.col, select, filter, with_columns, group_by) are mapped directly alongside their Pandas counterparts.

Q4. What machine learning evaluation formulas are summarized?

The cheat sheet includes formulas for Precision, Recall, F1-Score, ROC-AUC, Mean Absolute Error (MAE), Root Mean Squared Error (RMSE), and R-squared.

Q5. Can I use this cheat sheet for university lab exams?

Yes. The syntax conventions follow standard computer science laboratory coursework across Indian and global universities (BCA, MCA, B.Tech).

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

NumPy Mastery: Vectorization & Arrays

Detailed explanations of array creation, indexing, and vectorization.

Pandas DataFrames Manipulation & Indexing

In-depth syntax walkthrough for Series and DataFrame operations.

Polars Lightning-Fast DataFrame Engine

Fast reference for Polars expressions and lazy query execution.

130+ Data Science Interview Q&A

Test your mastery of the cheat sheet with technical interview questions.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!