Sum one row of a NumPy array
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 signific开发者_运维问答ant time penalty.
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:
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.
精彩评论