How to use numpy.hsplit in Python

In this tutorial, we will learn how to use the np.hsplit() of NumPy in Python with the help of an example. We will also see the syntax.

Using NumPy np.hsplit() in Python

In Python, the syntax numpy.hsplit() is used to split a list or an array into multiple sub-arrays horizontally. Let us see how to do this using a simple example.

Firstly we have to import the library NumPy into python. Next, we declare a list or an array which we wish to split.

import numpy as np

# Declare the array which is to be split
X = np.array([[1,2,3,4,5,6,7,8])

Once the array is declared, we decide how we want to split it. Suppose, we want to split the given array into 4 sub-arrays consisting of two elements each. Here’s how we do it.

Y=np.hsplit(X, 4)



[array([1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]

As a result, we see that the array has been split. Note that we can only split the array, in such a way that it results in the equal division of the array. This means that you cannot divide the given array into 3 sub-arrays.

Y=np.hsplit(X, 3)


TypeError: object of type 'int' has no len()

ValueError: array split does not result in an equal division

Hence, we can see that the splitting does not result into equal division of the array and the program gives an error.

Leave a Reply

Your email address will not be published. Required fields are marked *