Thenumpy.hsplit()
function is used to split aNumPy array into multiple sub-arrays horizontally (column-wise). It is equivalent to using thenumpy.split()
function withaxis=1
. Regardless of the dimensionality of the input array,numpy.hsplit()
always divides the array along its second axis (columns). This makes it particularly useful when you need to partition data based on columns for further processing or analysis.
Example:
Pythonimportnumpyasnparr=np.array([[1,2,3,4],[5,6,7,8]])result=np.hsplit(arr,2)print(result)
Syntax:
numpy.hsplit(arr, indices_or_sections)
- Parameters : arr : [ndarray] Array to be divided into sub-arrays.
- indices_or_sections : [int or 1-D array] If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis.
If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split .
- Return : [ndarray] A list of sub-arrays.
Why Is It Called a "Horizontal" Split?
The term "horizontal split" might seem counter-intuitive because columns are vertical structures. However, the terminology emphasises thelogical arrangementof the sub-arrays after the split. When dividing an array column-wise, the resulting sub-arrays are laid outhorizontally next to each other.
Split Type | Description | Resulting Sub-arrays |
---|
Horizontal Split (hsplit ) | Divides the arraycolumn-wise | Sub-arrays areside by side (horizontally) |
---|
Vertical Split (vsplit ) | Divides the arrayrow-wise | Sub-arrays arestacked vertically (one on top of another) |
---|
Code Implementation
Code #1 : The 4x4 array is split into two 4x2 sub-arrays.
Pythonimportnumpyasgeekarr=geek.arange(16.0).reshape(4,4)gfg=geek.hsplit(arr,2)print(gfg)
Output :
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[ 12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
Code #2 : The 3D array remains unchanged as it is split into a single section along the second axis.
Pythonimportnumpyasgeekarr=geek.arange(27.0).reshape(3,3,3)gfg=geek.hsplit(arr,1)print(gfg)
Output :
[array([[[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]],
[[ 9., 10., 11.],
[ 12., 13., 14.],
[ 15., 16., 17.]],
[[ 18., 19., 20.],
[ 21., 22., 23.],
[ 24., 25., 26.]]])]
In this article, we learned hownumpy.hsplit()
splits arrays horizontally (column-wise) along the second axis. We explored its syntax, practical examples with 2D and 3D arrays, and clarified the term "horizontal split."