NumPy Tutorial NumPy Statistics NumPy References

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.
  • If indices_or_sections is an integer, N, the array will be divided into N equal arrays horizontally. If such a split is not possible, an error is raised.
  • If indices_or_sections is a 1-D array of sorted integers, the entries indicate where the array is split horizontally.
  • If an index exceeds the dimension of the array horizontally, an empty sub-array is returned correspondingly.

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 - Array Manipulation