python 20 lines · 1 tab

Feature engineering for recency, frequency, and monetary behavior

1 tab
import pandas as pd

orders = pd.read_parquet('orders.parquet')
orders['ordered_at'] = pd.to_datetime(orders['ordered_at'])

reference_date = orders['ordered_at'].max() + pd.Timedelta(days=1)

features = (
    orders.groupby('customer_id')
    .agg(
        recency_days=('ordered_at', lambda values: (reference_date - values.max()).days),
        frequency=('order_id', 'nunique'),
        monetary=('amount', 'sum'),
        avg_basket=('amount', 'mean'),
    )
    .reset_index()
)

features['monetary_per_order'] = features['monetary'] / features['frequency'].clip(lower=1)
print(features.head())
1 file · python Explain with highlit

Tabular models improve fast when you encode behavior rather than raw events. Recency, frequency, and monetary aggregates are durable baseline features for retention, fraud, and conversion use cases. I usually build them in pure pandas first, then port them to a scheduled feature pipeline once the signal is proven.


Related snips

python
import pandas as pd

df = pd.read_csv('customers.csv')

df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_', regex=False)

Cleaning missing values and normalizing messy CSV exports

pandas data-cleaning missing-values
by Dr. Elena Vasquez 1 tab
python
import pandas as pd

df = pd.read_csv('traffic.csv', parse_dates=['timestamp'])
df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True)
df = df.set_index('timestamp').sort_index()

Time series resampling and rolling windows in pandas

pandas time-series resampling
by Dr. Elena Vasquez 1 tab
python
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

Encoding categorical variables without creating leakage

categorical-encoding preprocessing scikit-learn
by Dr. Elena Vasquez 1 tab
sql
WITH ordered_events AS (
  SELECT
    customer_id,
    event_time,
    revenue,
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_time DESC) AS event_rank,

SQL window functions for feature extraction and behavioral ranking

sql window-functions feature-engineering
by Dr. Elena Vasquez 1 tab
python
import pandas as pd

df = pd.read_parquet('events.parquet')
df['event_date'] = pd.to_datetime(df['event_date'])
df['month'] = df['event_date'].dt.to_period('M').astype(str)

GroupBy aggregations and pivot tables for business reporting

pandas groupby pivot-table
by Dr. Elena Vasquez 1 tab
python
import pandas as pd

df = pd.read_csv(
    'orders.csv',
    parse_dates=['created_at'],
    dtype={

pandas DataFrame essentials: loading, indexing, and selection

pandas python dataframe
by Dr. Elena Vasquez 1 tab

Share this code

Here's the card — post it anywhere.

Feature engineering for recency, frequency, and monetary behavior — share card
Link copied