gpt4 book ai didi

python - itertools product() 函数与总和

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:51 24 4
gpt4 key购买 nike

我有一个包含多个列的数据框 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') --> Ax 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

关于python - itertools product() 函数与总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54927383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com