如何计算二维 numpy 数组的所有列的总和(有效) [英] How to calculate the sum of all columns of a 2D numpy array (efficiently)

查看:37
本文介绍了如何计算二维 numpy 数组的所有列的总和(有效)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下由四行三列组成的二维 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 参数.对列求和:

<预><代码>>>>将 numpy 导入为 np>>>a = np.arange(12).reshape(4,3)>>>a.sum(axis=0)数组([18, 22, 26])

或者,对行求和:

<预><代码>>>>a.sum(axis=1)数组([ 3, 12, 21, 30])

其他聚合函数,如numpy.mean, numpy.cumsumnumpy.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:

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:

这篇关于如何计算二维 numpy 数组的所有列的总和(有效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆