NumPy 中矩阵的列之和
    
    Manav Narula
    2023年1月30日
    
    NumPy
    
- 
          
            在 Python 中使用 
numpy.sum()函数查找矩阵的列总和 - 
          
            在 Python 中使用 
numpy.einsum()函数查找矩阵的列总和 - 
          
            在 Python 中使用 
numpy.dot()函数查找矩阵的列总和 
本教程将介绍如何在 NumPy 中沿列查找元素的总和。
我们将计算以下矩阵的总和。
import numpy as np
a = np.arange(12).reshape(4, 3)
print(a)
输出:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
在 Python 中使用 numpy.sum() 函数查找矩阵的列总和
sum() 函数计算指定轴上数组中所有元素的总和。如果将轴指定为 0,则它将计算矩阵中各列的总和。
以下代码对此进行了说明。
import numpy as np
a = np.arange(12).reshape(4, 3)
s = np.sum(a, axis=0)
print(s)
输出:
[18 22 26]
在本教程中讨论的所有方法中,该方法是最常用和最快的。
在 Python 中使用 numpy.einsum() 函数查找矩阵的列总和
einsum() 是 NumPy 中有用而又复杂的函数。难以解释,因为它可以根据条件以各种方式找到总和。我们可以使用它来计算矩阵的列之和,如下所示。
import numpy as np
a = np.arange(12).reshape(4, 3)
s = np.einsum("ij->j", a)
print(s)
输出:
[18 22 26]
ij->j 是该函数的下标,该函数用于指定我们需要计算数组列的总和。
在 Python 中使用 numpy.dot() 函数查找矩阵的列总和
    
这是一个无关紧要的方法,但了解 dot() 函数的广泛使用仍应为人所知。如果我们用一个仅包含 1 的单行数组来计算 2-D 数组的点积,则会得到该矩阵的列之和。
以下代码实现了这一点。
import numpy as np
a = np.arange(12).reshape(4, 3)
s = np.dot(a.T, np.ones(a.shape[0]))
print(s)
输出:
[18. 22. 26.]
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Manav Narula
    Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn