What I do
- Create features from raw data for ML models
- Transform variables for better model performance
- Handle categorical and numerical features
- Create interaction and polynomial features
- Extract features from text, dates, and images
- Handle missing data strategically
- Select most predictive features
When to use me
Use me when:
- Preparing data for ML models
- Improving model performance
- Working with raw/unstructured data
- Handling complex data types
- Reducing feature dimensionality
Key Concepts
Feature Engineering Techniques
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
# Numerical transformations
df["log_income"] = np.log1p(df["income"])
df["income_squared"] = df["income"] ** 2
df["income_bucket"] = pd.cut(df["income"], bins=[0, 30, 60, 100],
labels=["low", "mid", "high"])
# Date features
df["order_date"] = pd.to_datetime(df["order_date"])
df["order_year"] = df["order_date"].dt.year
df["order_month"] = df["order_date"].dt.month
df["order_dayofweek"] = df["order_date"].dt.dayofweek
df["is_weekend"] = df["order_dayofweek"].isin([5, 6]).astype(int)
# Aggregation features
user_stats = df.groupby("user_id").agg({
"order_id": "count",
"total_amount": ["sum", "mean", "std"],
"order_date": ["min", "max"]
}).reset_index()
# Merge back
df = df.merge(user_stats, on="user_id", how="left")
# Text features
df["title_length"] = df["title"].str.len()
df["word_count"] = df["title"].str.split().str.len()
df["has_exclamation"] = df["title"].str.contains("!").astype(int)
# Categorical encoding
# One-hot encoding
pd.get_dummies(df, columns=["category"], prefix="cat")
# Target encoding
mean_encoding = df.groupby("category")["target"].mean()
df["category_encoded"] = df["category"].map(mean_encoding)
Feature Selection
- Filter methods: Correlation, chi-square
- Wrapper methods: RFE, forward selection
- Embedded methods: LASSO, feature importance
Handling Imbalanced Data
- SMOTE oversampling
- Undersampling majority class
- Class weights in model
- Focal loss
1---2name: feature-engineering3description: Machine learning feature engineering4license: MIT5---67## What I do89- Create features from raw data for ML models10- Transform variables for better model performance11- Handle categorical and numerical features12- Create interaction and polynomial features13- Extract features from text, dates, and images14- Handle missing data strategically15- Select most predictive features1617## When to use me1819Use me when:20- Preparing data for ML models21- Improving model performance22- Working with raw/unstructured data23- Handling complex data types24- Reducing feature dimensionality2526## Key Concepts2728### Feature Engineering Techniques29```python30import pandas as pd31import numpy as np32from sklearn.preprocessing import StandardScaler, OneHotEncoder33from sklearn.impute import SimpleImputer3435# Numerical transformations36df["log_income"] = np.log1p(df["income"])37df["income_squared"] = df["income"] ** 238df["income_bucket"] = pd.cut(df["income"], bins=[0, 30, 60, 100], 39 labels=["low", "mid", "high"])4041# Date features42df["order_date"] = pd.to_datetime(df["order_date"])43df["order_year"] = df["order_date"].dt.year44df["order_month"] = df["order_date"].dt.month45df["order_dayofweek"] = df["order_date"].dt.dayofweek46df["is_weekend"] = df["order_dayofweek"].isin([5, 6]).astype(int)4748# Aggregation features49user_stats = df.groupby("user_id").agg({50 "order_id": "count",51 "total_amount": ["sum", "mean", "std"],52 "order_date": ["min", "max"]53}).reset_index()5455# Merge back56df = df.merge(user_stats, on="user_id", how="left")5758# Text features59df["title_length"] = df["title"].str.len()60df["word_count"] = df["title"].str.split().str.len()61df["has_exclamation"] = df["title"].str.contains("!").astype(int)6263# Categorical encoding64# One-hot encoding65pd.get_dummies(df, columns=["category"], prefix="cat")6667# Target encoding68mean_encoding = df.groupby("category")["target"].mean()69df["category_encoded"] = df["category"].map(mean_encoding)70```7172### Feature Selection73- **Filter methods**: Correlation, chi-square74- **Wrapper methods**: RFE, forward selection75- **Embedded methods**: LASSO, feature importance7677### Handling Imbalanced Data78- SMOTE oversampling79- Undersampling majority class80- Class weights in model81- Focal loss