w3resource

Advanced NumPy Exercises - Find the sum along the last axis of a 3x3x3 array

NumPy: Advanced Exercise-8 with Solution

Write a NumPy program to create a 3x3x3 array with random values and find the sum along the last axis.

To work with a 3x3x3 array in NumPy, you can create an array filled with random values using numpy.random.rand. To find the sum along the last axis, use the numpy.sum function with the axis parameter set to 2. This operation will sum the elements along the innermost axis (i.e., the third dimension) for each 3x3 sub-array within the overall 3D array.

Sample Solution:

Python Code:

import numpy as np
nums = np.random.rand(3, 3, 3)
print("Original array elements:")
print(nums)
sum_along_last_axis = np.sum(nums, axis=2)
print("\nSum along the last axis:")
print(sum_along_last_axis)

Output:

Original array elements:
[[[0.66542849 0.8452917  0.14572805]
  [0.07553346 0.77602774 0.65256042]
  [0.64461145 0.80786691 0.29072733]]

 [[0.20943008 0.32606894 0.15482057]
  [0.13066528 0.36319837 0.83379825]
  [0.71210716 0.69634548 0.75775974]]

 [[0.14054546 0.61485173 0.42188979]
  [0.63975373 0.02786896 0.77550368]
  [0.81748415 0.15730395 0.86243833]]]

Sum along the last axis:
[[1.65644824 1.50412161 1.74320568]
 [0.69031959 1.32766189 2.16621238]
 [1.17728698 1.44312636 1.83722642]]

Explanation:

In the above exercise -

nums = np.random.rand(3, 3, 3): This creates a 3-dimensional array of shape (3, 3, 3) with random values between 0 and 1.

sum_along_last_axis = np.sum(nums, axis=2): This code calculates the sum along the last axis of the nums array, which has an index of 2. It creates a new 2-dimensional array of shape (3, 3) where each element is the sum of the corresponding values in the original array along the last axis.

Python-Numpy Code Editor:

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

Previous: Normalize a 5x5 array row-wise with random values.
Next: Create a 5x5 array with random values and sort each row.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/numpy/advanced-numpy-exercise-8.php