Splitting divides arrays into multiple sub-arrays either vertically (vsplit
) or horizontally (hsplit
).
Code Example:
import numpy as np
# Creating a 4x4 array for demonstration
arr = np.arange(16).reshape(4, 4)
# Splitting the array into 2 vertically
vsplit_arr = np.vsplit(arr, 2)
# Splitting the array into 2 horizontally
hsplit_arr = np.hsplit(arr, 2)
print("Original Array:\n", arr)
print("\nAfter Vertical Split:\nFirst Part:\n", vsplit_arr[0], "\nSecond Part:\n", vsplit_arr[1])
print("\nAfter Horizontal Split:\nFirst Part:\n", hsplit_arr[0], "\nSecond Part:\n", hsplit_arr[1])
PythonOutput:
Original Array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
After Vertical Split:
First Part:
[[0 1 2 3]
[4 5 6 7]]
Second Part:
[[ 8 9 10 11]
[12 13 14 15]]
After Horizontal Split:
First Part:
[[ 0 1]
[ 4 5]
[ 8 9]
[12 13]]
Second Part:
[[ 2 3]
[ 6 7]
[10 11]
[14 15]]
PythonExplanation:
np.vsplit(arr, 2)
splits the arrayarr
into two vertically, creating two sub-arrays each with half the rows of the original.np.hsplit(arr, 2)
splits the arrayarr
into two horizontally, each sub-array containing half the columns of the original.