NumPy: Calculate the sum of all columns of a 2D NumPy array
NumPy: Array Object Exercise-152 with Solution
Sum all columns of a 2D array.
Write a NumPy program to calculate the sum of all columns in a 2D NumPy array.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Generating a NumPy array 'num' containing numbers from 0 to 35 using arange()
num = np.arange(36)
# Reshaping the array 'num' into a 4x9 matrix and assigning it to 'arr1'
arr1 = np.reshape(num, [4, 9])
# Displaying a message indicating the original array will be printed
print("Original array:")
# Printing the original array 'arr1'
print(arr1)
# Computing the sum of each column of the array 'arr1' along axis 0 (columns) and storing it in 'result'
result = arr1.sum(axis=0)
# Displaying a message indicating the sum of all columns will be printed
print("\nSum of all columns:")
# Printing the sum of each column of the array 'arr1'
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]
Explanation:
This above code demonstrates how to use NumPy to find the sum of elements along the columns of a 2D array.
num = np.arange(36): This code creates a 1D NumPy array called num with elements from 0 to 35.
arr1 = np.reshape(num, [4, 9]): This code reshapes the num array into a 2D array ‘arr1’ with 4 rows and 9 columns.
result = arr1.sum(axis=0): This code calculates the sum of elements along the columns (axis=0) of the 2D array ‘arr1’. The result is a 1D array with the same length as the number of columns in ‘arr1’.
Pictorial Presentation:
Python-Numpy Code Editor:
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 Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-152.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics