带sum的itertools product()函数

2024-05-13 00:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有几个列的数据帧a,我想把所有这些列“加起来”得到一个数据帧B

A = [col1 col2 col3 
       0    1    2
       1    1    0
      -1    0    1]

B应该看起来像:

^{pr2}$

基本上,这个操作背后的理念正是嵌入到itertools.product()得到笛卡尔积的函数。在

在itertools.product('ABCD','xy')-->;Ax Ay Bx By Cx Cy Dx Dy

我只需要运用同样的原理得到:
函数\u smg('ABCD','xy')-->;A+x A+y B+x B+y C+x C+y D+x D+y

我的数据帧很大,所以我负担不起循环,我需要一个迭代器或生成器。 如果没有函数能做到这一点,我如何构建一个生成器来实现这一点呢?在

非常感谢


Tags: 数据函数gtproductax理念col2col3
2条回答

这里有一种方法。您可以使用^{}从现有列中获取所有长度为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])]

压缩后的元组与每个值相加:

^{pr2}$

或者如果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

相关问题 更多 >