Kodeclik Blog

# How to use numpy.sum() in Python

Consider a two dimensional numpy array of numbers such as:

```
import numpy as np
myarray = [[1.5,2.5,3,3.5],
[1.5,2,3.5,3]]
```

numpy.sum() is a handy function that can return the sum of elements in the given array. All you need to do is to pass the array as input:

`print(np.sum(myarray))`

This produces the output:

`20.5`

You can verify that the sum of all the elements (all 8 of them) add up to 20.5.

numpy.sum() is quite versatile. It can be used to sum elements across specified dimensions.

For instance, the above array has two rows and 4 columns. If we were to sum along the first axis (i.e., rows) we will obtain a result which has one row and 4 columns. We accomplish this by specifying a “axis=0” when we call numpy.sum():

```
import numpy as np
myarray = [[1.5,2.5,3,3.5],
[1.5,2,3.5,3]]
print(np.sum(myarray,axis=0))
```

The output is:

`[3. 4.5 6.5 6.5]`

Similarly, if we were to sum along the second axis (i.e., columns) we will obtain a result which has 2 rows and one column:

```
import numpy as np
myarray = [[1.5,2.5,3,3.5],
[1.5,2,3.5,3]]
print(np.sum(myarray,axis=1))
```

The output is:

`[10.5 10. ]`

A second feature of numpy.sum() is that it can take an initial value and begins calculating sums from that point. So for instance, if we take the code above and slightly modify the invocation to numpy.sum() like so:

```
import numpy as np
myarray = [[1.5,2.5,3,3.5],
[1.5,2,3.5,3]]
print(np.sum(myarray,axis=1,initial=-10))
```

The results will be:

`[0.5 0. ]`

because -10 is added to the original sums, i.e., [10.5 10. ], yielding [0.5, 0].

So to summarize, the numpy.sum() function can be used to calculate the sum of an array or list of numbers in one step and can save you a great deal of time and effort as opposed to say, writing a loop. Adapt it in your own programs and tell us where you found it useful!

If you enjoyed this blogpost about numpy.sum() in Python, learn about the Python reduce function.

For more Python content, checkout the math.ceil() and math.floor() functions! Also

learn about the math domain error in Python and how to fix it!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.