[英]itertools: Getting combinations of operations ( + - * / ) and columns
Given a data frame of numeric values, I would like to perform plus, minus, multiply & divide on all combinations of columns.给定一个数值数据框,我想对所有列组合执行加、减、乘和除。
What would be the fastest approach to do this for combinations of 3 and above?对于 3 及以上的组合,最快的方法是什么?
A minimal reproducible example is given below with combinations of 2.下面给出了一个最小的可重现示例,其中包含 2 的组合。
import numpy as np
import pandas as pd
from itertools import combinations
from itertools import permutations
from sklearn.datasets import load_boston
# the dataset
X, y = load_boston(return_X_y=True)
X = pd.DataFrame(X)
combos2 = list(combinations(X.columns,2))
perm3 = list(permutations(X.columns,3)) # how would i do this with out typing out all the permutations
for i in combos2:
X[f'{i[0]}_X_{i[1]}'] = X.iloc[:,i[0]]*X.iloc[:,i[1]] # Multiply
X[f'{i[0]}_+_{i[1]}'] = X.iloc[:,i[0]]+X.iloc[:,i[1]] # Add
X[f'{i[0]}_-_{i[1]}'] = X.iloc[:,i[0]]-X.iloc[:,i[1]] # Subtract
X[f'{i[0]}_/_{i[1]}'] = X.iloc[:,i[0]]/(X.iloc[:,i[1]]+1e-20) # Divide
I was thinking of a way to add the "operators + * - / into the combinations so it can be written in fewer lines than manually typing out all the combinations, but I don't know where to begin?我正在考虑一种将“运算符 + * - /”添加到组合中的方法,这样它可以用更少的行来编写,而不是手动输入所有组合,但我不知道从哪里开始?
I would like all orders: ie (a * b + c), (a * b - c), (a * b / c) etc我想要所有订单:即 (a * b + c)、(a * b - c)、(a * b / c) 等
Ideally leaving no duplicate columns.理想情况下不留下重复的列。 ie (a + b + c) and (c + b + a)
即 (a + b + c) 和 (c + b + a)
For example if I had 3 columns ab c.例如,如果我有 3 列 ab c。 I want a new column (a * b + c).
我想要一个新列(a * b + c)。
I hope this will help you get started:我希望这可以帮助您入门:
operators = ['-', '+', '*', '/']
operands = ['a', 'b', 'c']
# find out all possible combination of operators first. So if you have 3 operands, that would be all permutations of the operators, taken 2 at a time. Also append the same expression operator combinations to the list
from itertools import permutations
operator_combinations = list(permutations(operators, len(operands)-1))
operator_combinations.extend([op]*(len(operands)-1) for op in operators)
# create a list for each possible expression, appending it with an operand and then an operator and so on, finishing off with an operand.
exp = []
for symbols in operator_combinations:
temp = []
for o,s in zip(operands, symbols):
temp.extend([o,s])
temp.append(operands[-1])
exp.append(temp)
for ans in exp:
print(''.join(ans))
Output: Output:
a-b+c
a-b*c
a-b/c
a+b-c
a+b*c
a+b/c
a*b-c
a*b+c
a*b/c
a/b-c
a/b+c
a/b*c
a-b-c
a+b+c
a*b*c
a/b/c
Here's a naive solution that outputs the combinations of 2 & 3 of all the columns.这是一个简单的解决方案,它输出所有列的 2 和 3 的组合。
from sklearn.datasets import load_boston
from itertools import combinations
import operator as op
X, y = load_boston(return_X_y=True)
X = pd.DataFrame(X)
comb= list(combinations(X.columns,3))
def operations(x,a,b):
if (x == '+'):
d = op.add(a,b)
if (x == '-'):
d = op.sub(a,b)
if (x == '*'):
d = op.mul(a,b)
if (x == '/'): # divide by 0 error
d = op.truediv(a,(b + 1e-20))
return d
for x in ['*','/','+','-']:
for y in ['*','/','+','-']:
for i in comb:
a = X.iloc[:,i[0]].values
b = X.iloc[:,i[1]].values
c = X.iloc[:,i[2]].values
d = operations(x,a,b)
e = operations(y,d,c)
X[f'{i[0]}{x}{i[1]}{y}{i[2]}'] = e
X[f'{i[0]}{x}{i[1]}'] = d
X = X.loc[:,~X.columns.duplicated()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.