Skip to content

Instantly share code, notes, and snippets.

@eug
Created November 17, 2016 19:58
Show Gist options
  • Save eug/0f673a3a52b78d876df67a0f4863a80a to your computer and use it in GitHub Desktop.
Save eug/0f673a3a52b78d876df67a0f4863a80a to your computer and use it in GitHub Desktop.
Generate a new feature matrix consisting of all arithmetic combinations of the features.
def arithmetic_features(X, operations=['+', '-', '/', '*'], commutative=False, inplace=False):
df = X
if not inplace:
df = X.copy()
from itertools import combinations
for x, y in combinations(df.columns, 2):
if '+' in operations:
df['%s+%s' % (x, y)] = df[x] + df[y]
if '*' in operations:
df['%s*%s' % (x, y)] = df[x] * df[y]
if '/' in operations:
df['%s/%s' % (x, y)] = df[x] / df[y]
if commutative:
df['%s/%s' % (y, x)] = df[y] / df[x]
if '-' in operations:
df['%s-%s' % (x, y)] = df[x] - df[y]
if commutative:
df['%s-%s' % (y, x)] = df[y] - df[x]
return df
import pandas as pd
df = pd.DataFrame({'A':[1,2,3,4,5,6,7,8,9,10], 'B':[10,9,8,7,6,5,4,3,2,1]})
print(arithmetic_features(df))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment