Sum one line of a NumPy array

I would like to summarize one specific line of a large NumPy array. I know that the function array.max() will give the maximum for the entire array, and array.max(1) will give me the maximum for each of the lines as an array. However, I would like to get the maximum on a specific line (for example, line 7 or line 29). I have a large array, so getting the maximum for all rows will give me a significant time penalty.

+6
performance python arrays numpy
source share
1 answer

You can easily access a row of a two-dimensional array using the index operator. The string itself is an array, a representation of part of the original array and provides all array methods, including sum() and max() . Therefore, you can easily get the maximum per line as follows:

 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. 
+19
source share

All Articles