w3resource

NumPy: Calculate the sum of all columns of a 2D NumPy array

NumPy: Array Object Exercise-152 with Solution

Write a NumPy program to calculate the sum of all columns of a 2D NumPy array.

Sample Solution:

Python Code:

import numpy as np
num = np.arange(36)
arr1 = np.reshape(num, [4, 9])
print("Original array:")
print(arr1)
result  = arr1.sum(axis=0)
print("\nSum of all columns:")
print(result)

Sample Output:

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

Sum of all columns:
[54 58 62 66 70 74 78 82 86]

Pictorial Presentation:

NumPy: Calculate the sum of all columns of a 2D NumPy array

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to get the row numbers in given array where at least one item is larger than a specified value.
Next: Write a NumPy program to extract upper triangular part of a NumPy matrix.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]