Sum of NumPy Array in Python (3 Examples)
In this article, I’ll explain how to apply the np.sum function in Python.
The content of the tutorial looks as follows:
If you want to learn more about these content blocks, keep reading…
Example Data & Libraries
We first have to load the NumPy library, to be able to use the functions that are contained in the library:
import numpy as np # Load NumPy library
Next, let’s also define some example data in Python:
my_array = np.array([[1, 2, 3], [4, 5, 6]]) # Create example array print(my_array) # Print example array # [[1 2 3] # [4 5 6]]
As you can see based on the previously shown output of the Python console, our example data is an array containing six values in three different columns.
Example 1: Sum of All Values in NumPy Array
The following code demonstrates how to calculate the sum of all elements in a NumPy array.
For this task, we can apply the sum function of the NumPy library as shown below:
print(np.sum(my_array)) # Get sum of all array values # 21
As shown by the previous output, the sum of all values in our array is 21.
Example 2: Sum of Columns in NumPy Array
In Example 2, I’ll show how to find the sum of the values in a NumPy array column-wise.
To achieve this, we have to set the axis argument within the NumPy sum function to 0:
print(np.sum(my_array, axis = 0)) # Get sum of array columns # [5 7 9]
Example 3: Sum of Rows in NumPy Array
Similar to Example 2, we can also perform an addition of the values in a NumPy array by row.
For this, we have to specify the axis argument to be equal to 1:
print(np.sum(my_array, axis = 1)) # Get sum of array rows # [ 6 15]
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. I illustrate the Python programming codes of this post in the video.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you could have a look at some of the other tutorials on this website:
- Calculate Sum in Python
- Find Sum by Group in Python
- Convert pandas DataFrame Index to List & NumPy Array in Python
- Get Median of Array with np.median Function of NumPy Library in Python
- Convert pandas DataFrame to NumPy Array in Python
- The Python Programming Language
At this point you should know how to use the np.sum function to get the sum of an array in the Python programming language. Let me know in the comments section below, if you have further questions.