NumPy - hsplit() function
The NumPy hsplit() function splits an array into multiple sub-arrays horizontally (column-wise).
Syntax
numpy.hsplit(ary, indices_or_sections)
Parameters
ary |
Required. Specify the array (ndarray) to be divided into sub-arrays. |
indices_or_sections |
Required. Specify indices_or_sections as int or 1-D array.
|
Return Value
Returns a list of sub-arrays as views into ary.
Example:
In the example below, hsplit() function is used to split a given array.
import numpy as np Arr = np.array([[10, 20, 30], [30, 40, 60], [70, 80, 90]]) #splitting the array Arr1 = np.hsplit(Arr, 3) #displaying results print("Arr is:") print(Arr) print("\nArr1 is:") print(Arr1)
The output of the above code will be:
Arr is: [[10 20 30] [30 40 60] [70 80 90]] Arr1 is: [array([[10], [30], [70]]), array([[20], [40], [80]]), array([[30], [60], [90]])]
Example: indices_or_sections as 1-D array
When indices_or_sections is passed as 1-D array of sorted integers, the entries indicate where the array is split horizontally. Consider the following example.
import numpy as np Arr = np.array([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 200, 300]]) #splitting the array Arr1 = np.hsplit(Arr, [2,3]) #displaying results print("Arr is:") print(Arr) print("\nArr1 is:") print(Arr1)
The output of the above code will be:
Arr is: [[ 10 20 30 40] [ 50 60 70 80] [ 90 100 200 300]] Arr1 is: [array([[ 10, 20], [ 50, 60], [ 90, 100]]), array([[ 30], [ 70], [200]]), array([[ 40], [ 80], [300]])]
❮ NumPy - Functions