如何针对 Python 中的每个行排列快速跨列求和

How to quickly sum across columns for every permutation of rows in Python

假设我有一个 n x k 矩阵 X。我想得到各列的总和,但对于行的每个排列。因此,如果我的矩阵是 [[1,2],[3,4]],我想要的输出将是 [1+2, 1+4, 3+2, 3+4]。我第一次尝试解决方案时制作了一个 MWE 示例。我希望我能得到一些帮助来减少计算时间。

我的实际问题有n=160k=4,到运行需要相当长的时间(写这篇文章的时候,还是运行ning)。

import pandas as pd
import numpy as np
import itertools

n = 4
k = 3

X = np.random.randint(0, 10, (n, k))
df = pd.DataFrame(X)
df
   0  1  2
0  2  9  2
1  7  6  4
2  3  7  0
3  5  0  0
ixi = df.index.tolist()
ixc = df.columns.tolist()

psum = np.array([df.lookup(i, ixc).sum() for i in 
                 itertools.product(ixi, repeat=len(ixc))])

你可以试试functools.reduce:

from functools import reduce
reduce(np.add.outer, df.values.T).ravel()