Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

NumPy Array Split

Splitting NumPy Arrays

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.

Example

Divide the array into 3 parts:

import numpy as np

arr = np.array([123456])

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.

Example

Divide the array into 4 parts:

import numpy as np

arr = np.array([123456])

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.