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:
For more Practice: Solve these Related Problems:
- Write a NumPy program to vertically split a 2D array into sub-arrays using np.vsplit.
 - Create a function that divides a 2D array into equal vertical chunks and validates each segment's shape.
 - Test vertical splitting on an array with an odd number of rows and handle the remainder appropriately.
 - Implement a solution using np.split with axis=0 and compare it to the output of np.vsplit.
 
Go to:
PREV : Stack 1D Arrays as Rows
NEXT :  Split Array Along 3rd Axis
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
