NumPy: Split a given array into multiple sub-arrays vertically
NumPy: Array Object Exercise-131 with Solution
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:
Previous: Write a NumPy program to stack 1-D arrays as row wise.
Next: Write a NumPy program to split array into multiple sub-arrays along the 3rd axis.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/python-exercises/numpy/python-numpy-exercise-131.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics