假设我有以下由四行三列组成的二维 numpy 数组:
>>> a = numpy.arange(12).reshape(4,3)
>>> print(a)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
生成包含所有列之和的一维数组(如 [18,22,26]
)的有效方法是什么?这可以在不需要遍历所有列的情况下完成吗?
最佳答案
查看 numpy.sum
的文档,特别注意 axis
参数。总结列:
>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])
或者,对行求和:
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
其他聚合函数,如 numpy.mean
, numpy.cumsum
和 numpy.std
,例如,也带 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:
关于python - 如何计算 2D numpy 数组的所有列的总和(有效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567345/