numpy.hsplit() function | Python (original) (raw)
Last Updated : 07 Apr, 2025
The**numpy.hsplit()
** function is used to split a NumPy array into multiple sub-arrays horizontally (column-wise). It is equivalent to using the **numpy.split() function with axis=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:
Python `
import numpy as np arr = 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 the **logical arrangement of the sub-arrays after the split. When dividing an array column-wise, the resulting sub-arrays are laid out **horizontally next to each other.
Split Type | Description | Resulting Sub-arrays |
---|---|---|
Horizontal Split (hsplit) | Divides the array **column-wise | Sub-arrays are **side by side (horizontally) |
Vertical Split (vsplit) | Divides the array **row-wise | Sub-arrays are **stacked vertically (one on top of another) |
Code Implementation
**Code #1 : The 4×4 array is split into two 4×2 sub-arrays.
Python `
import numpy as geek arr = 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.
Python `
import numpy as geek arr = 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 how numpy.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.”