我有一个包含多个列的数据帧A,我想将所有这些列“与他们自己”相加以获得数据帧B.
A = [col1 col2 col3
0 1 2
1 1 0
-1 0 1]
和B应该看起来像:
B = [col1+col2 col1+col3 col2+col3
1 2 3
2 1 1
-1 0 1]
基本上,这个操作背后的哲学正是嵌入在itertools.product()函数中的,它产生了一个笛卡尔积。
itertools.product('ABCD','xy') - > Axe Ay Bx By Cx Cy Dx Dy
我只需要应用相同的原则并得到: function_smg('ABCD','xy') - > A + x A + y B + x B + y C + x C + y D + x D + y
我的数据框很大,所以我买不起循环,我需要一个迭代器或一个生成器。如果没有功能可以解决问题,我该如何构建一个生成器呢?
非常感谢
这是一种方法。您可以先使用itertools.combinations
从现有列中获取所有长度为2的组合:
from itertools import combinations
c = combinations(df.T.values.tolist(), 2)
# [([0, 1, -1], [1, 1, 0]), ([0, 1, -1], [2, 0, 1]), ([1, 1, 0], [2, 0, 1])]
然后将每个元组的值加在一起压缩:
from itertools import starmap
from operator import add
l = [list(starmap(add,zip(i,j))) for i,j in c]
pd.DataFrame(l, index=df.columns).T
col1 col2 col3
0 1 2 3
1 2 1 1
2 -1 0 1
或者如果numpy
也是一个选项:
import numpy as np
c = list(combinations(df.T.values.tolist(), 2))
pd.DataFrame(np.array(c).sum(1), index=df.columns).T
col1 col2 col3
0 1 2 3
1 2 1 1
2 -1 0 1
对于这个问题,实际上比itertools产品更精确。试试itertools combinations
import pandas as pd
from itertools import combinations
A = pd.DataFrame({"col1": [0, 1, -1],
"col2": [1, 1, 0],
"col3": [2, 0, 1]})
B = pd.DataFrame() #Create an empty dataframe first
for col1, col2 in combinations(A.columns, 2):
B[f"{col1}+{col2}"] = A[col1] + A[col2] #Create columns one by one.
#B["{}+{}".format(col1, col2)] = A[col1] + A[col2] (Before python 3.6)
print(B)
#Output:
col1+col2 col1+col3 col2+col3
0 1 2 3
1 2 1 1
2 -1 0 1