如何有效地计算2D numpy数组的所有列的总和 [英] How to calculate the sum of all columns of a 2D numpy array (efficiently)
问题描述
假设我有以下由四行三列组成的2D numpy数组:
Let's say I have the following 2D numpy array consisting of four rows and three columns:
>>> a = numpy.arange(12).reshape(4,3)
>>> print(a)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
生成包含所有列之和的一维数组的有效方法是什么(如[18, 22, 26]
)?不需要遍历所有列就可以做到吗?
What would be an efficient way to generate a 1D array that contains the sum of all columns (like [18, 22, 26]
)? Can this be done without having the need to loop through all columns?
推荐答案
查看或者,对行求和:
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
其他聚合函数,例如 numpy.mean
, numpy.cumsum
和
Other aggregate functions, like numpy.mean
, numpy.cumsum
and numpy.std
, e.g., also take the axis
parameter.
许多一元运算,例如计算所有元素的总和 在数组中,作为
ndarray
类的方法实现.经过 默认情况下,这些操作适用于数组,就好像它是一个列表一样 不论其形状如何.但是,通过指定axis
您可以沿参数的指定轴应用操作的参数 数组:
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the
ndarray
class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying theaxis
parameter you can apply an operation along the specified axis of an array:
这篇关于如何有效地计算2D numpy数组的所有列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!