如何计算2D numpy数组中所有列的和(高效)

2024-04-24 06:53:39 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下2D numpy数组,由四行三列组成:

>>> a = numpy.arange(12).reshape(4,3)
>>> print(a)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

生成包含所有列之和的1D数组(如[18, 22, 26])的有效方法是什么?不需要遍历所有列就可以完成吗?


Tags: 方法numpy数组printarangereshape
3条回答

使用axis参数:

>> numpy.sum(a, axis=0)
  array([18, 22, 26])

查看^{}的文档,特别注意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])

其他聚合函数,如^{}^{}^{},例如,也接受axis参数。

Tentative Numpy Tutorial

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 the axis parameter you can apply an operation along the specified axis of an array:

使用^{}。对你来说,是的

sum = a.sum(axis=0)

相关问题 更多 >