w3resource

NumPy: Split array into multiple sub-arrays along the 3rd axis

NumPy: Array Object Exercise-132 with Solution

Split Array Along 3rd Axis

Write a NumPy program to split an array into multiple sub-arrays along the 3rd axis.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Printing a message indicating the original array will be displayed
print("\nOriginal arrays:")

# Creating a NumPy array 'x' with elements from 0 to 15 and reshaping it into a 3-dimensional array of shape (2, 2, 4)
x = np.arange(16.0).reshape(2, 2, 4)

# Displaying the original 3D array 'x'
print(x)

# Splitting the 3D array 'x' into two sub-arrays along the third axis using np.dsplit()
new_array1 = np.dsplit(x, 2)

# Printing a message indicating the splitting of the array along the 3rd axis and displaying the resulting sub-arrays
print("\nsplit array into multiple sub-arrays along the 3rd axis:")
print(new_array1) 

Sample Output:

Original arrays:
[[[ 0.  1.  2.  3.]
  [ 4.  5.  6.  7.]]

 [[ 8.  9. 10. 11.]
  [12. 13. 14. 15.]]]

split array into multiple sub-arrays along the 3rd axis:
[array([[[ 0.,  1.],
        [ 4.,  5.]],

       [[ 8.,  9.],
        [12., 13.]]]), array([[[ 2.,  3.],
        [ 6.,  7.]],

       [[10., 11.],
        [14., 15.]]])]

Explanation:

In the above code –

x = np.arange(16.0).reshape(2, 2, 4): It creates a 3-dimensional NumPy array x of shape (2, 2, 4) with elements from 0.0 to 15.0.

new_array1 = np.dsplit(x, 2): This line splits the 3-dimensional array x into two equal parts depth-wise (along the third axis). The result is a list of two 3-dimensional arrays, each of shape (2, 2, 2):

Pictorial Presentation:

Python NumPy: Split array into multiple sub-arrays along the 3rd axis.

Python-Numpy Code Editor:

Previous: Write a NumPy program to split an given array into multiple sub-arrays vertically (row-wise).
Next: Write a NumPy program to count the number of dimensions, number of elements and number of bytes for each element in a given array.

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://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-132.php