python - 如何计算 2D numpy 数组的所有列的总和(有效)

标签 python numpy

假设我有以下由四行三列组成的二维 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.cumsumnumpy.std ,例如,也带 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:

关于python - 如何计算 2D numpy 数组的所有列的总和(有效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567345/

相关文章:

python - 通过 int 选择 numpy 数组轴

python - 更新列表中的元组

python - Pandas:将 WinZipped csv 文件转换为 Data Frame

Python 和 curl 问题

Python DataFrame - 为具有分组列(至少两列)的数据框绘制条形图

python - 迭代时如何获取 2D Numpy 数组中的位置?

python - 沿轴连接 numpy 字符串数组?

python - 为什么底部打印顺序不正确?

python - 不可散列类型 : 'numpy.ndarray' error in tensorflow

时间序列的Python聚合