Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带sum的itertools product()函数_Python_Generator_Itertools - Fatal编程技术网

Python 带sum的itertools product()函数

Python 带sum的itertools product()函数,python,generator,itertools,Python,Generator,Itertools,我有一个包含多个列的数据框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

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

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

我的数据帧是巨大的,所以我负担不起循环,我需要一个迭代器或生成器。 如果没有函数可以实现这个技巧,我如何构建一个生成器来实现呢


非常感谢

对于这个问题,实际上有比itertools产品更精确的东西。试一试


这里有一种方法。首先,可以使用以下方法从现有列中获取所有长度为2的组合:

然后添加压缩在一起的每个元组中的值:

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.product('ABCD','xy')
产生
('A','x'),('A','y')。。。('D','y')
,因此当对其进行迭代时,您可以将一个元组传递给
sum()
或类似的适当函数,如
str.join()
math.fsum()
。然后,您的生成器看起来像
(itertools.product('ABCD','xy')中p的总和(p))
谢谢yatu,我认为这可能非常有用!良好的矢量化问题:)检查numpy解决方案以获得更好的性能@cyrilmuay
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
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