Skip to main content
 首页 » 编程设计

python之每两列相加

2025年05月04日10yjmyzz

我想计算矩阵中两列中两个的总和(第 0 列和第 1 列之间的总和,第 2 列和第 3 列之间...)。

所以我尝试做嵌套的“for”循环,但每次都没有好的结果。

例如:

c = np.array([[0,0,0.25,0.5],[0,0.5,0.25,0],[0.5,0,0,0]],float) 
freq=np.zeros(6,float).reshape((3, 2)) 
 
#I calculate the sum between the first and second column, and between the fird and the fourth column 
for i in range(0,4,2): 
    for j in range(1,4,2): 
        for p in range(0,2): 
            freq[:,p]=(c[:,i]+c[:,j]) 

但结果是:

 print freq            
 array([[ 0.75,  0.75], 
        [ 0.25,  0.25], 
        [ 0.  ,  0.  ]]) 

通常好的结果必须是 (0., 0.5,0.5) 和 (0.75,0.25,0)。所以我认为问题出在嵌套的“for”循环中。

有没有人知道我如何计算每两列的总和,因为我有一个包含 400 列的矩阵?

请您参考如下方法:

您可以简单地 reshape 以将最后一个维度拆分为两个维度,最后一个维度的长度为 2,然后对其求和,就像这样 -

freq = c.reshape(c.shape[0],-1,2).sum(2).T 

reshape 只会创建数组的 View ,因此非常有效,我们只是在这里使用求和操作,因此必须高效。

sample 运行-

In [17]: c 
Out[17]:  
array([[ 0.  ,  0.  ,  0.25,  0.5 ], 
       [ 0.  ,  0.5 ,  0.25,  0.  ], 
       [ 0.5 ,  0.  ,  0.  ,  0.  ]]) 
 
In [18]: c.reshape(c.shape[0],-1,2).sum(2).T 
Out[18]:  
array([[ 0.  ,  0.5 ,  0.5 ], 
       [ 0.75,  0.25,  0.  ]])