Reading history

Feature Engineering in Python: Dates, Ratios and Log Transforms

7 min read 0 views

Learn feature engineering in Python with pandas: extract hour and weekday from dates, build ratio features like BMI, and use log transforms on skewed data.

A model can only learn from the columns you give it. Feature engineering means building new columns that make the pattern easier to see. Often a simple new column helps more than switching to a fancier model. In this lesson you will split timestamps into useful parts, combine two columns into a ratio, and use a log to tame skewed numbers.

In this lesson you will learn

  • What feature engineering is and why it helps
  • How to extract hour, weekday and weekend flags from dates in pandas
  • How a ratio feature such as BMI can replace two raw columns
  • When a log transform turns a curve into a straight line
  • How to engineer features without leaking information

You should know linear regression, decision trees and random forests and basic pandas.

Why New Columns Help

Raw data is stored in the way that is easy to record, not in the way that is easy to learn from. A timestamp is one long number. A person’s size is stored as height and weight. A salary column may run from 5,000 to 5,000,000. Each of these hides the real pattern a little. Feature engineering uses what you know about the problem to bring that pattern out.

Features From Dates and Times

We have hourly bike rentals for 120 days. On weekdays people ride to work at 8am and home at 6pm. At weekends they ride around midday.

0369121518210255075100Hour of dayAverage rentalsWeekday: peaks at 8am and 6pmWeekend: one midday hump
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

# Hourly bike rentals for 120 days. Demand peaks at 8am and 6pm on
# weekdays and around midday at weekends.
rng = np.random.default_rng(3)
times = pd.date_range("2026-01-01", periods=120 * 24, freq="h")
hour, wd = times.hour.to_numpy(), times.dayofweek.to_numpy()
weekend = wd >= 5
rush = np.exp(-(hour - 8) ** 2 / 2) + np.exp(-(hour - 18) ** 2 / 2)
midday = np.exp(-(hour - 13) ** 2 / 8)
rentals = np.where(weekend, 60 * midday, 80 * rush) + 10 + rng.normal(0, 3, len(times))
rentals = np.clip(rentals, 0, None)
df = pd.DataFrame({"time": times, "rentals": rentals.round()})

# Feature engineering: turn one timestamp into parts a model can use
df["hour"] = df["time"].dt.hour
df["weekday"] = df["time"].dt.dayofweek
df["is_weekend"] = (df["weekday"] >= 5).astype(int)
df["raw_number"] = (df["time"] - pd.Timestamp("1970-01-01")) // pd.Timedelta("1h")  # hours since 1970
print(df.head(3).to_string(index=False))

def r2(cols):
    X_tr, X_te, y_tr, y_te = train_test_split(df[cols], df["rentals"], shuffle=False)
    model = RandomForestRegressor(n_estimators=100, random_state=0).fit(X_tr, y_tr)
    return model.score(X_te, y_te)

print(f"\nraw timestamp only       : R2 = {r2(['raw_number']):.3f}")
print(f"hour, weekday, is_weekend: R2 = {r2(['hour', 'weekday', 'is_weekend']):.3f}")

Output

               time  rentals  hour  weekday  is_weekend  raw_number
2026-01-01 00:00:00     16.0     0        3           0      490896
2026-01-01 01:00:00      2.0     1        3           0      490897
2026-01-01 02:00:00     11.0     2        3           0      490898

raw timestamp only       : R2 = -0.222
hour, weekday, is_weekend: R2 = 0.983
  • The .dt accessor pulls parts out of a date column: .hour, .dayofweek (Monday is 0), .month and more.
  • As one raw number, time only grows. The model learns “rentals at this point in time”, which says nothing about future hours. Its R² is below zero, which means it is worse than always guessing the average.
  • With hour, weekday and a weekend flag, the same forest scores 0.983. Every future Monday at 8am now looks like the Mondays it has seen.
  • We used shuffle=False so the test set is the last part of the period, just like real forecasting.

Ratio Features

Health risk depends on weight compared with height, not on either one alone. A tall person can be heavy and healthy. We use a small decision tree with only two levels so the effect is easy to see.

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score

rng = np.random.default_rng(5)
n = 600
height = rng.normal(1.65, 0.09, n)                 # metres
weight = rng.normal(65, 13, n)                     # kilograms
bmi = weight / height ** 2
at_risk = (bmi + rng.normal(0, 1.5, n) > 27).astype(int)
people = pd.DataFrame({"height": height, "weight": weight})

# 1) A ratio feature: one BMI column replaces a diagonal boundary
model = DecisionTreeClassifier(max_depth=2, random_state=0)   # a small tree
plain = cross_val_score(model, people, at_risk, cv=5).mean()
people["bmi"] = people["weight"] / people["height"] ** 2
with_bmi = cross_val_score(model, people[["bmi"]], at_risk, cv=5).mean()
print(f"height + weight : accuracy {plain:.3f}")
print(f"bmi alone       : accuracy {with_bmi:.3f}")

# 2) A log feature: spending grows with the LOG of income
income = rng.lognormal(10, 0.8, n)                  # very skewed
spend = 3000 * np.log(income) + rng.normal(0, 1500, n)
raw = cross_val_score(LinearRegression(), income.reshape(-1, 1), spend, cv=5).mean()
logged = cross_val_score(LinearRegression(), np.log(income).reshape(-1, 1), spend, cv=5).mean()
print(f"\nincome as is    : R2 {raw:.3f}")
print(f"log(income)     : R2 {logged:.3f}")

Output

height + weight : accuracy 0.845
bmi alone       : accuracy 0.942

income as is    : R2 0.548
log(income)     : R2 0.738
  • The true boundary depends on weight and height together, so it runs on a slant through the data. A tree can only cut straight across one column at a time. With two levels it cannot follow a slanted line, so it reaches only 84.5%.
  • BMI turns the slanted boundary into a single cut-off, so one split is enough and accuracy jumps to 94.2%.
  • Other useful ratios: price per square foot, debt divided by income, goals per match, clicks per visit.

Log Transforms for Skewed Numbers

The second half of fe2.py looks at income. A few people earn far more than most, so the column is badly skewed. Spending grows with income, but each extra taka matters less at the top. That is the shape of a log curve. A straight line through raw income fits poorly (R² 0.548). A line through log(income) fits well (R² 0.738). Use np.log1p instead of np.log when a column can contain zeros.

A Menu of Feature Ideas

Raw dataNew features
Date and timeHour, weekday, month, weekend flag, holiday flag, days since an event
Two related numbersRatio, difference, product
Skewed amountsLog, square root, bins
TextLength, word count, has a number, TF-IDF
Transactions per customerCount, total, average, days since last purchase
LocationDistance to the city centre or nearest shop

Stay safe from leakage

Features built from one row alone, such as hour or BMI, are safe. Features built from many rows, such as “average spend of this customer’s city”, must be learned on training rows only. Put them in a pipeline step. See data leakage for why.

Common Mistakes

  1. Feeding a raw timestamp to a model. Extract the parts that repeat, such as hour and weekday.
  2. Adding hundreds of random features. Each feature should come from an idea about the problem. Noise columns can hurt.
  3. Using information from the future. “Total purchases this year” is unknown in March. Build features only from data before the prediction moment.
  4. Taking the log of zero or negative numbers. Use log1p for zeros, and check the minimum first.

Practice Exercises

Exercise 1. Hours 23 and 0 are next to each other, but as numbers they are far apart. How can you encode the hour so the model sees it as a circle?

Show answer
df["hour_sin"] = np.sin(2 * np.pi * df["hour"] / 24)
df["hour_cos"] = np.cos(2 * np.pi * df["hour"] / 24)

The two columns place each hour on a clock face, so 23:00 and 00:00 end up close together. This helps linear models most; trees handle plain hours well.

Exercise 2. You predict whether a loan will be repaid. You have monthly_income and monthly_loan_payment. Suggest one engineered feature.

Show answer

payment_to_income = monthly_loan_payment / monthly_income. A payment that eats half of someone’s income is far riskier than the same payment for a higher earner.

Frequently Asked Questions

Do tree models need feature engineering?

Less than linear models, because trees handle curves and skewed values on their own. They still gain a lot from features they cannot build, such as ratios, date parts and counts per customer.

Is feature engineering still useful with deep learning?

For images, sound and text, deep networks learn their own features. For tables of business data, hand-made features remain one of the best ways to improve a model.

Summary

  • Feature engineering builds columns that expose the pattern.
  • Split timestamps into repeating parts like hour and weekday.
  • Ratios capture how two columns work together.
  • Logs straighten skewed, curved relationships.

Next: Decision Tree From Scratch in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *