All snippets assume df (rows to transform) and train (the training split, the only place statistics are
learned). Wrap them in a function or a scikit-learn transformer so the same code runs in training and serving.
Dates and timestamps
d = pd.to_datetime(df["event_ts"], errors="coerce", utc=True)
df["month"] = d.dt.month
df["dow"] = d.dt.day_of_week # 0 = Monday
df["hour"] = d.dt.hour
df["is_weekend"] = (d.dt.day_of_week >= 5).astype(int)
df["day_of_month"] = d.dt.day
df["is_month_end"] = d.dt.is_month_end.astype(int)
# Elapsed time to the prediction time (scoring date per row, or a fixed cutoff)
df["days_since_signup"] = (pd.to_datetime(df["score_date"]) - pd.to_datetime(df["signup_date"])).dt.days
# Cyclical encodings (linear / distance models): hour 23 is next to hour 0
df["hour_sin"] = np.sin(2 * np.pi * df["hour"] / 24)
df["hour_cos"] = np.cos(2 * np.pi * df["hour"] / 24)
df["dow_sin"] = np.sin(2 * np.pi * df["dow"] / 7)
df["dow_cos"] = np.cos(2 * np.pi * df["dow"] / 7)Holidays and events: holidays package (holidays.country_holidays("US")) or a company calendar; add
days_to_next_holiday and days_since_last_holiday for demand problems.
Unix epochs: pd.to_datetime(df["ts"], unit="s") (or unit="ms").
Do not feed the raw timestamp or a monotonically increasing date to a tree model trained on a random split: it learns "period" effects that do not exist in the future.
Time zones: compute hour/day-of-week in the user's local time when behaviour is local (shopping, logins).
Years
df["building_age"] = df["score_date"].dt.year - df["year_built"]Amounts and other skewed positives
df["log_amount"] = np.log1p(df["amount"].clip(lower=0))
lo, hi = train["amount"].quantile([0.01, 0.99])
df["amount_clip"] = df["amount"].clip(lo, hi)
df["amount_is_round"] = (df["amount"] % 10 == 0).astype(int) # fraud: round amounts
df["amount_cents"] = (df["amount"] * 100 % 100).round() # fraud/testing patternsTrees are invariant to monotone transforms: log1p helps linear, k-NN and neural models, not GBMs (except via ratios and interactions).
Counts
df["log_tickets"] = np.log1p(df["tickets_90d"])
df["tickets_per_month"] = df["tickets_total"] / df["tenure_months"].clip(lower=1)
df["has_tickets"] = (df["tickets_90d"] > 0).astype(int)Low-cardinality categoricals
keep = train["plan"].value_counts()
keep = keep[keep >= 20].index
df["plan"] = df["plan"].where(df["plan"].isin(keep), "other")Then one-hot (OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=20)) for linear models, or
native categoricals for LightGBM / CatBoost / HistGradientBoosting. Ordinal categories (small < medium <
large) get an ordinal integer.
High-cardinality categoricals
freq = train["merchant_id"].value_counts()
df["merchant_freq"] = df["merchant_id"].map(freq).fillna(0)
from sklearn.preprocessing import TargetEncoder # sklearn >= 1.3; cross-fitted inside fit_transform
te = TargetEncoder(target_type="binary", cv=5, smooth="auto")See categorical-encoding-selector for the full decision table (hashing, CatBoost ordered target statistics, embeddings).
Codes with hierarchy
df["zip3"] = df["zip_code"].astype(str).str.zfill(5).str[:3]
df["naics2"] = df["naics"].astype(str).str[:2]
df["icd_chapter"] = df["icd10"].str[0]Join external attributes by code (census income by zip, industry risk by NAICS) when allowed.
Geography
def haversine_km(lat1, lon1, lat2, lon2):
lat1, lon1, lat2, lon2 = map(np.radians, (lat1, lon1, lat2, lon2))
a = np.sin((lat2 - lat1) / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2 - lon1) / 2) ** 2
return 2 * 6371.0 * np.arcsin(np.sqrt(a))
df["dist_to_store_km"] = haversine_km(df.lat, df.lon, df.store_lat, df.store_lon)
df["grid_cell"] = (df.lat.round(2).astype(str) + "_" + df.lon.round(2).astype(str)) # ~1 km cellsFraud: distance between billing and shipping address, between consecutive transactions divided by elapsed time ("impossible travel").
Text
df["desc_len"] = df["description"].str.len()
df["desc_words"] = df["description"].str.split().str.len()
df["desc_has_urgent"] = df["description"].str.contains(r"\burgent|asap\b", case=False, regex=True).astype(int)
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(ngram_range=(1, 2), min_df=5, max_features=20000, sublinear_tf=True)TF-IDF goes inside the ColumnTransformer so it is fitted on training text only. For semantic signal use sentence embeddings, reduced with PCA/TruncatedSVD if the model is a GBM.
Missingness
for c in ["monthly_charges", "last_payment_amount"]:
df[f"{c}_missing"] = df[c].isna().astype(int)SimpleImputer(add_indicator=True) does this inside a pipeline. A column missing only for positives (filled
after the event) is a leak, not a feature.
Booleans and flags
Keep as 0/1. Combine related flags into counts (n_products_owned) and ratios.
anomaly-detection-model-builder
Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.
catboost-model-builder
Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).
categorical-encoding-selector
Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).
classification-model-selector
Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.
clustering-algorithm-selector
Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.
collaborative-filtering-implementer
Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.