Splitting is the opposite of joining; while joining merges multiple arrays into one, splitting divides a single array into several sub-arrays. We use the array_split() function to split an array, specifying the number of parts.
Divide the array into 3 parts:
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) newarr = np.array_split(arr, 3) print(newarr) |
If the array has fewer elements than needed, it will adjust the split from the end accordingly.
Divide the array into 4 parts:
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) newarr = np.array_split(arr, 4) print(newarr) |
Note: The split() method is also available, but unlike array_split(), it does not adjust when the source array has fewer elements than needed for the split. In such cases, split() would fail, while array_split() works correctly. |