HOW TO SPLIT PYTHON NUMPY ARRAY?

Splitting Python NumPy Arrays

The array_split() method is used for splitting arrays, by passing it the array we want to split and the number of splits.

It will returns the list of arrays.

If the array has less elements than required as per split specified, it will adjust from the end accordingly.

We can also specify which axis we want to do the split around.

import numpy as np

arr1 = np.array([1, 2, 3, 4, 5, 6])

arr2 = np.array_split(arr1, 2)
print(arr2)

arr3 = np.array([1, 2, 3, 4, 5, 6, 7])
arr4 = np.array_split(arr3, 2) #element adjusted from end
print(arr4)

arr5 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
arr6 = np.array_split(arr5, 2)
print(arr4)

arr7 = np.array_split(arr5, 2, 1)
print(arr7)

Output-

[array([1, 2, 3]), array([4, 5, 6])]
[array([1, 2, 3, 4]), array([5, 6, 7])]
[array([1, 2, 3, 4]), array([5, 6, 7])]
[array([[ 1,  2],
       [ 4,  5],
       [ 7,  8],
       [10, 11]]), array([[ 3],
       [ 6],
       [ 9],
       [12]])]

An alternate solution is using hsplit() opposite of hstack() Similar alternates to vstack() and dstack() are available as vsplit() and dsplit().


Posted

in

Tags:

Comments

Leave a Reply