NumPy: Calculate the sum of all columns of a 2D NumPy array
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:
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:
For more Practice: Solve these Related Problems:
- Write a NumPy program to compute the column-wise sums of a 2D array and then subtract the overall row sum from each column.
- Create a function that returns both the sum and mean of each column in a given matrix.
- Implement a solution that uses np.sum with axis=0 and then applies a transformation to the summed result.
- Test the column summing operation on an array with negative and positive values to validate the output.
Go to:
PREV : Get rows where elements are larger than a specified value.
NEXT : Extract upper triangular part of a matrix.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.