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.
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
| 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"]) |
-- 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)
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')
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Detailed explanations of array creation, indexing, and vectorization.
In-depth syntax walkthrough for Series and DataFrame operations.
Fast reference for Polars expressions and lazy query execution.
Test your mastery of the cheat sheet with technical interview questions.