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

Published: December 05, 2019

DMCA.com Protection Status

Example of how to sum a column of data in python with numpy:

Sum a given column of data

Let's consider the following matrix

>>> 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]])

\begin{equation}
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)
\end{equation}

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

\begin{equation}
data[:,0] = \left( \begin{array}{ccc}
0 \\
10 \\
20 \\
30 \\
40 \\
50 \\
60 \\
70
\end{array}\right)
\end{equation}

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

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

\begin{equation}
data[:,4] = \left( \begin{array}{ccc}
4 \\
14 \\
24 \\
34 \\
44 \\
54 \\
64 \\
74
\end{array}\right)
\end{equation}

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

Another example, to sum the numbers of the last column data[:,-1]:

\begin{equation}
data[:,-1] = \left( \begin{array}{ccc}
9 \\
19 \\
29 \\
39 \\
49 \\
59 \\
69 \\
79
\end{array}\right)
\end{equation}

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

Create a function that iterate over the column

Another example:

>>> def col_sum(data,col_idx):
...     r = 0
...     for i in range(data.shape[0]):
...             r = r + data[i,col_idx]
...     return r
... 
>>> 
>>> col_sum(data,0)
280
>>> col_sum(data,4)
312
>>> col_sum(data,9)
352

References

Links Site
sum() python doc