NumPy: Split a given array into multiple sub-arrays vertically
Split Array Vertically
Write a NumPy program to split a given array into multiple sub-arrays vertically (row-wise).
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 4x4 array
x = np.arange(16.0).reshape(4, 4)
# Displaying the original 4x4 array 'x'
print(x)
# Splitting the array 'x' into two sub-arrays vertically using np.vsplit()
new_array1 = np.vsplit(x, 2)
# Printing a message indicating the vertical splitting of the array and displaying the resulting sub-arrays
print("\nSplit an array into multiple sub-arrays vertically:")
print(new_array1)
Sample Output:
Original arrays: [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.] [12. 13. 14. 15.]] Split an array into multiple sub-arrays vertically: [array([[0., 1., 2., 3.], [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.], [12., 13., 14., 15.]])]
Explanation:
In the above code –
x = np.arange(16.0).reshape(4, 4): It creates a 2-dimensional NumPy array x of shape (4, 4) with elements from 0.0 to 15.0.
new_array1 = np.vsplit(x, 2): It splits the 2-dimensional array x into two equal parts vertically (along the rows).
Finally print() function prints the new_array1.
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