Split Array into Smaller Arrays - NumPy
NumPy - Split array into smaller arrays
To split a numpy array into smaller arrays, you can use the numpy function numpy.array_split().
The syntax to call array_split() function is
numpy.array_split(arr, n)where
arris the array you want to split.nis the number of smaller arrays you want to split arrayarrinto.
We can also use numpy.split() function. The syntax of split() function is
numpy.split(arr, indices, axis)where
arris the array you want to split.indicesare the indices at which you want to split the arrayarr.axisis the axis along which the split has to be done.
Examples
1. Split array into 4 smaller arrays
In the following program, we take a numpy array (one dimensional) of length 12, and split the array into 4 smaller arrays.
Python Program
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
output = np.array_split(arr, 4)
print(output)Output
[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9]), array([10, 11, 12])]2. Split array at specific indices
In the following program, we take a numpy array (one dimensional), and split the array at indices 3 and 7.
Python Program
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
output = np.array_split(arr, [3, 7])
print(output)Output
[array([1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11, 12])]Explanation
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] <- arr
0 1 2 3 4 5 6 7 8 9 10 11 <- indices
|3 |7
[1, 2, 3][4, 5, 6, 7][8, 9, 10, 11, 12] <- splitsSummary
In this NumPy Tutorial , we learned how to split a numpy array into smaller arrays using numpy.array_split() and numpy.split() functions.