# How to sum a given row of a data array in python with numpy ?

Daidalos December 05, 2019

Example of how to sum a given row of a data array in python with numpy:

### Sum a row of data

Lets consider the following array:

>>> import numpy as np
>>> data =  np.arange(80).reshape((8, 10))
>>> data
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74, 75, 76, 77, 78, 79]])


data = \left( \begin{array}{ccc}
0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \\
10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 \\
20 & 21 & 22 & 23 & 24 & 25 & 26 & 27 & 28 & 29 \\
30 & 31 & 32 & 33 & 34 & 35 & 36 & 37 & 38 & 39 \\
40 & 41 & 42 & 43 & 44 & 45 & 46 & 47 & 48 & 49 \\
50 & 51 & 52 & 53 & 54 & 55 & 56 & 57 & 58 & 59 \\
60 & 61 & 62 & 63 & 64 & 65 & 66 & 67 & 68 & 69 \\
70 & 71 & 72 & 73 & 74 & 75 & 76 & 77 & 78 & 79
\end{array}\right)

To add together the numbers of the first row data[0,:], a solution is to use the function sum() :

data[0,:] = \left( \begin{array}{ccc}
0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9
\end{array}\right)

>>> sum(data[0,:])
45


Another example, to sum the numbers of the 5th row data[4,:]:

data[4,:] = \left( \begin{array}{ccc}
40 & 41 & 42 & 43 & 44 & 45 & 46 & 47 & 48 & 49
\end{array}\right)

>>> sum(data[4,:])
445


Another example, to sum the last rown data[:-1,:]:

data[-1,:] = \left( \begin{array}{ccc}
70 & 71 & 72 & 73 & 74 & 75 & 76 & 77 & 78 & 79
\end{array}\right)

>>> sum(data[-1,:])
745


### Create a function that iterate over the row

Another example:

>>> def row_sum(data,row_idx):
...     r = 0
...     for j in range(data.shape[1]):
...             r = r + data[row_idx,j]
...     return r
... 
>>> 
>>> row_sum(data,0)
45
>>> row_sum(data,4)
445
>>> row_sum(data,7)
745