NumPy: Split array into multiple sub-arrays along the 3rd axis
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 Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics