Skip to content

Feature Engineering

Feature engineering creates new variables from existing data. Good features give models more signal, and on tabular data they often matter more than the choice of algorithm. This page uses a synthetic clinical dataset with numeric, date, text, and categorical columns.

Every code block runs in a container in the companion repository, so the numbers are real.

import numpy as np
import pandas as pd
np.random.seed(42)
n = 500
df = pd.DataFrame({
"admission_date":
pd.date_range("2020-01-01", periods=n, freq="2D"),
"discharge_date":
pd.date_range("2020-01-03", periods=n, freq="2D") +
pd.to_timedelta(np.random.randint(1, 14, n), unit="D"),
"age":
np.random.normal(55, 15, n).astype(int),
"weight_kg":
np.random.normal(75, 15, n).round(1),
"height_cm":
np.random.normal(170, 10, n).round(1),
"systolic_bp":
np.random.normal(130, 20, n).astype(int),
"diastolic_bp":
np.random.normal(80, 12, n).astype(int),
"glucose_mg_dl":
np.random.lognormal(4.6, 0.3, n).round(1),
"diagnosis_text":
np.random.choice([
"Type 2 diabetes with neuropathy", "Hypertension stage 2",
"Chronic kidney disease stage 3", "Acute myocardial infarction",
"Heart failure with reduced ejection fraction"
], n),
"medication":
np.random.choice(
["metformin", "lisinopril", "amlodipine", "insulin", "aspirin"], n),
"lab_result":
np.random.choice(["normal", "low", "high", "critical"], n),
})

The most valuable features come from domain knowledge. Combine columns into quantities with known clinical meaning.

df["bmi"] = df["weight_kg"] / (df["height_cm"] / 100)**2
df["pulse_pressure"] = df["systolic_bp"] - df["diastolic_bp"]
df["map_pressure"] = df["diastolic_bp"] + df["pulse_pressure"] / 3
print(df[["weight_kg", "height_cm", "bmi"]].head().to_string(index=False))
weight_kg height_cm bmi
74.9 176.8 23.961682
95.4 167.3 34.084466
72.8 162.5 27.569231
64.8 178.7 20.292049
102.2 181.3 31.092475

BMI, pulse pressure, and mean arterial pressure carry more meaning than the raw inputs.

Many biological measurements are right-skewed. A log transform brings them closer to normal, which helps linear models. Use np.log1p to handle zeros.

print(f"Glucose skewness before log: {df['glucose_mg_dl'].skew():.2f}")
df["log_glucose"] = np.log1p(df["glucose_mg_dl"])
print(f"Glucose skewness after log: {df['log_glucose'].skew():.2f}")
Glucose skewness before log: 0.86
Glucose skewness after log: 0.11

Binning turns a continuous variable into categories, useful when the effect changes at known thresholds.

df["age_group"] = pd.cut(df["age"],
bins=[0, 40, 55, 65, 100],
labels=["young", "middle", "senior", "elderly"])
print(df["age_group"].value_counts().sort_index().to_string(header=False))
outside = df.loc[df["age_group"].isna(), "age"].tolist()
print(f"Ages outside the bins: {outside}")
young 91
middle 161
senior 113
elderly 134
Ages outside the bins: [102]

The four counts cover every patient but one. The simulated age of 102 lies above the last bin edge of 100, so pd.cut leaves that patient without a group and value_counts does not count it.

Dates are not directly usable. Extract numeric components and durations.

df["admission_month"] = df["admission_date"].dt.month
df["admission_dayofweek"] = df["admission_date"].dt.dayofweek
df["length_of_stay"] = (df["discharge_date"] - df["admission_date"]).dt.days
df["is_weekend_admission"] = df["admission_dayofweek"].isin([5, 6]).astype(int)
date_columns = ["admission_date", "admission_month", "admission_dayofweek",
"length_of_stay", "is_weekend_admission"]
print(df[date_columns].head().to_string(index=False))
admission_date admission_month admission_dayofweek length_of_stay is_weekend_admission
2020-01-01 1 2 9 0
2020-01-03 1 4 6 0
2020-01-05 1 6 15 1
2020-01-07 1 1 13 0
2020-01-09 1 3 10 0

Month captures seasonality, day of week captures weekend effects, and time differences capture duration.

Free-text fields hold signal the structured columns miss. Start with keyword flags.

df["diagnosis_word_count"] = df["diagnosis_text"].str.split().str.len()
df["has_diabetes"] = df["diagnosis_text"].str.contains("diabetes",
case=False).astype(int)
df["has_heart"] = df["diagnosis_text"].str.contains("heart|myocardial|cardiac",
case=False).astype(int)
df["has_kidney"] = df["diagnosis_text"].str.contains("kidney|renal",
case=False).astype(int)
text_columns = ["diagnosis_word_count", "has_diabetes", "has_heart",
"has_kidney"]
print(df[text_columns].head().to_string(index=False))
diagnosis_word_count has_diabetes has_heart has_kidney
6 0 1 0
3 0 1 0
3 0 1 0
6 0 1 0
6 0 1 0

For more general text, TF-IDF turns text into weighted numeric vectors.

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(max_features=10, stop_words="english")
mat = tfidf.fit_transform(df["diagnosis_text"])
tfidf_df = pd.DataFrame(mat.toarray(),
columns=tfidf.get_feature_names_out())
# One row per term, one column per patient, for the first three patients.
print(tfidf_df.head(3).T.round(3).to_string())
0 1 2
acute 0.000 0.577 0.577
chronic 0.000 0.000 0.000
disease 0.000 0.000 0.000
ejection 0.577 0.000 0.000
heart 0.577 0.000 0.000
infarction 0.000 0.577 0.577
kidney 0.000 0.000 0.000
myocardial 0.000 0.577 0.577
reduced 0.577 0.000 0.000
stage 0.000 0.000 0.000

max_features=10 keeps the ten terms with the highest counts across all 500 rows. That vocabulary drops type, diabetes, neuropathy, hypertension, failure, and fraction, so every diabetes row becomes a vector of zeros and the heart failure rows keep only ejection, heart, and reduced. In each of the three rows above, the three kept terms always occur together, so they share one inverse document frequency and get the same weight, 0.577. On real notes, raise max_features or drop the limit, so that less frequent but informative terms such as diabetes stay in the vocabulary.

For ordered categories, map to integers that reflect the order:

df["lab_result_ordinal"] = df["lab_result"].map({
"normal": 0,
"low": 1,
"high": 2,
"critical": 3
})

For high-cardinality categoricals, frequency encoding replaces each category with its prevalence, avoiding a wide one-hot expansion:

med_freq = df["medication"].value_counts(normalize=True)
df["medication_freq"] = df["medication"].map(med_freq)
print(med_freq.round(3).to_string(header=False))
metformin 0.228
lisinopril 0.226
aspirin 0.202
amlodipine 0.184
insulin 0.160

PolynomialFeatures builds interaction terms automatically.

from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
poly.fit(df[["age", "bmi", "glucose_mg_dl"]])
names = poly.get_feature_names_out()
print(f"Input features: 3, output features: {len(names)}")
print(f"Names: {list(names)}")
wide = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
wide.fit(np.zeros((1, 20)))
print(f"Input features: 20, output features: {wide.n_output_features_}")
Input features: 3, output features: 6
Names: ['age', 'bmi', 'glucose_mg_dl', 'age bmi', 'age glucose_mg_dl', 'bmi glucose_mg_dl']
Input features: 20, output features: 210

interaction_only=True skips squared terms. Beware the explosion: 20 inputs at degree 2 give 210 features.

Technique Best for Watch out for
Domain features (BMI, ratios) All models Needs domain knowledge
Log transform Skewed numerics Helps tree models little
Binning Known threshold effects Loses information
Date extraction Time-based data Consider cyclical encoding
Keyword flags Short text, known terms Misses spelling variants
TF-IDF Longer text High dimensionality
Frequency encoding High-cardinality categoricals Compute inside CV to avoid leakage
Polynomial features Linear models Feature explosion

With features engineered and selected, the next pages cover specific algorithms. Start with Regression, the fundamental models every data scientist should understand.

  • PolynomialFeatures reference

    The reference defines degree, interaction_only, and include_bias. These settings determine which products appear and how many columns the transformation creates.

  • scikit-learn text feature extraction

    The guide explains token counts, vocabulary construction, and TF-IDF weighting. It also shows why a fitted text transformation belongs inside model evaluation.