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
arr
is the array you want to split.n
is the number of smaller arrays you want to split arrayarr
into.
We can also use numpy.split()
function. The syntax of split()
function is
numpy.split(arr, indices, axis)
where
arr
is the array you want to split.indices
are the indices at which you want to split the arrayarr
.axis
is 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] <- splits
Summary
In this NumPy Tutorial , we learned how to split a numpy array into smaller arrays using numpy.array_split() and numpy.split() functions.