Consider a two dimensional numpy array of numbers such as:
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:
This produces the output:
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():
The output is:
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:
The output is:
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:
The results will be:
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.
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!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.