pythonintermediate

Pandas Cartesian Feature Interaction

Generate pairwise feature interactions for ML by creating cross-product columns.

python
import pandas as pd
from itertools import combinations

df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]})
numeric_cols = ['A','B','C']

for c1, c2 in combinations(numeric_cols, 2):
    df[f'{c1}_{c2}_product'] = df[c1] * df[c2]
    df[f'{c1}_{c2}_ratio']   = df[c1] / df[c2].replace(0, float('nan'))

print(df)

Use Cases

  • ML feature engineering
  • polynomial features
  • interaction terms

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.