NumPy: Splitting NumPy Arrays

Splitting means breaking the single given array into multiple sub-arrays. We can split an array in the following ways:

np.split():

Numpy package contains a function split() which is used to break the array into multiple sub-arrays. It splits the array into equal divisions.

Syntax:

numpy.split(array, section,axis=0)

Here, we pass the parameters such as the array which we want to split and the number of splits along the specified axis.

Example:

For 1-D Array:

import numpy as np
a=np.arange(8)
print("a=",a)
c=np.split(a,4,axis=0)
print("After Splitting we get:",c)

Output:

a= [0 1 2 3 4 5 6 7]
After Splitting we get: [array([0, 1]), array([2, 3]), array([4, 5]), array([6, 7])]

For 2-D Array:

import numpy as np
a=np.array([[1,2],[3,4],[7,8],[9,10]])
b=np.split(a,4,axis=0)
print(b)

Output:

[array([[1, 2]]), array([[3, 4]]), array([[7, 8]]), array([[ 9, 10]])]

array_split():

It is also used for splitting the array.

Example:

For 1-D Array:

import numpy as np
a=np.arange(8)
print("a=",a)
c=np.array_split(a,5,axis=0)
print("After Splitting we get:",c)

Output:

a= [0 1 2 3 4 5 6 7]
After Splitting we get: [array([0, 1]), array([2, 3]), array([4, 5]), array([6]),
array([7])]

In the above example, we can see that array_split() is working properly. In case if we use split() in the above example we will get an error becauseĀ it will not adjust the elements when elements are less in the source array for splitting.

import numpy as np
a=np.arange(8)
print("a=",a)
c=np.split(a,5,axis=0)
print("After Splitting we get:",c)

Output:

a= [0 1 2 3 4 5 6 7]
ValueError: array split does not result in an equal division

For 2-D Array:

import numpy as np
a=np.array([[1,2],[3,4],[5,6]])
b=np.array_split(a,2)
print(b)

Output:

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