亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

itertools:獲取操作(+ - * /)和列的組合

itertools:獲取操作(+ - * /)和列的組合

胡說叔叔 2023-03-01 15:31:35
給定一個數值數據框,我想對所有列組合執行加、減、乘和除。對于 3 及以上的組合,最快的方法是什么?下面給出了一個最小的可重現示例,其中包含 2。import numpy as npimport pandas as pdfrom itertools import combinationsfrom itertools import permutationsfrom sklearn.datasets import load_boston # the datasetX, 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 permutationsfor 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我正在考慮一種將“運算符 + * - / 添加到組合中的方法,這樣它可以用比手動輸入所有組合更少的行來編寫,但我不知道從哪里開始?我想要所有訂單:即 (a * b + c) , (a * b - c) , (a * b / c) 等理想情況下不要留下重復的列。即(a + b + c)和(c + b + a)例如,如果我有 3 列 ab c。我想要一個新列 (a * b + c)。
查看完整描述

2 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

我希望這會幫助您入門:


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))

輸出 :


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


查看完整回答
反對 回復 2023-03-01
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

這是一個天真的解決方案,它輸出所有列的 2 和 3 的組合。

  1. 組合列表

  2. 使用 operator 包創建一個函數

  3. for循環組合

  4. 這可能有重復的列,因此刪除重復項

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()]


查看完整回答
反對 回復 2023-03-01
  • 2 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號