Python 对 NumPy 数组的一行求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4001067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:47:07  来源:igfitidea点击:

Sum one row of a NumPy array

pythonarraysperformancenumpy

提问by robintw

I'd like to sum one particular row of a large NumPy array. I know the function array.max()will give the maximum across the whole array, and array.max(1)will give me the maximum across each of the rows as an array. However, I'd like to get the maximum in a certain row (for example, row 7, or row 29). I have a large array, so getting the maximum for all rows will give me a significant time penalty.

我想对大型 NumPy 数组的某一行求和。我知道该函数array.max()将给出整个数组array.max(1)的最大值,并将作为数组的每一行给出最大值。但是,我想在某一行(例如,第 7 行或第 29 行)中获得最大值。我有一个很大的数组,所以获得所有行的最大值会给我带来很大的时间损失。

采纳答案by Ferdinand Beyer

You can easily access a row of a two-dimensional array using the indexing operator. The row itself is an array, a view of a part of the original array, and exposes all array methods, including sum()and max(). Therefore you can easily get the maximum per row like this:

您可以使用索引运算符轻松访问二维数组的一行。行本身是一个数组,是原始数组一部分的视图,并公开了所有数组方法,包括sum()max()。因此,您可以轻松获得每行的最大值,如下所示:

x = arr[7].max()   # Maximum in row 7
y = arr[29].sum()  # Sum of the values in row 29

Just for completeness, you can do the same for columns:

为了完整起见,您可以对列执行相同的操作:

z = arr[:, 5].sum()  # Sum up all values in column 5.