问题描述
假设我有以下由四行三列组成的二维 numpy 数组:
>>>a = numpy.arange(12).reshape(4,3)>>>打印(一)[[ 0 1 2][ 3 4 5][ 6 7 8][ 9 10 11]]生成包含所有列的总和的一维数组(如 [18, 22, 26]
)的有效方法是什么?这可以在不需要遍历所有列的情况下完成吗?
查看 numpy.sum
,特别注意axis
参数.对列求和:
或者,对行求和:
>>>a.sum(axis=1)数组([ 3, 12, 21, 30])其他聚合函数,如numpy.mean
, numpy.cumsum
和 numpy.std
,例如,还要带axis
参数.
来自 暂定 Numpy 教程:
许多一元运算,例如计算所有元素的总和在数组中,被实现为 ndarray
类的方法.经过默认情况下,这些操作适用于数组,就好像它是一个列表数字,无论其形状如何.但是,通过指定 axis
参数,您可以沿指定的轴应用操作数组:
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]]
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?
Check out the documentation for numpy.sum
, paying particular attention to the axis
parameter. To sum over columns:
>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])
Or, to sum over rows:
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
Other aggregate functions, like numpy.mean
, numpy.cumsum
and numpy.std
, e.g., also take the axis
parameter.
From the Tentative Numpy Tutorial:
这篇关于如何计算二维 numpy 数组的所有列的总和(有效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!