Splitting NumPy Arrays
Splitting is the reverse process of joining.
While joining combines multiple arrays into one, splitting breaks a single array into multiple parts.
To split arrays in NumPy, we use the array_split() method. It requires:
The array you want to split.
The number of splits.
Program:
Split 1-D 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)
Output:
Note:
The result is a list containing the split arrays.
If the number of elements in the array is not perfectly divisible, array_split() will adjust the splits automatically
Program:
Split 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)
Output:
Important:
NumPy also provides the split() method. However, unlike array_split(), split() does not handle cases where elements cannot be evenly split — it will raise an error in such cases.
Thus, array_split() is more flexible for uneven splits.
Accessing Split Arrays
You can access the individual arrays from the result just like you would with any list:
Program:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr[0]) # First part
print(newarr[1]) # Second part
print(newarr[2]) # Third part
Output:
Splitting 2-D Arrays
Splitting 2-D arrays works similarly.
You can specify both:
The number of splits.
The axis along which to split.
Program:
Split a 2-D Array into 3 Parts (Row-wise)
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)
Output:
Program:
Split 2-D Array with 3 Columns (Row-wise)
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
newarr = np.array_split(arr, 3)
print(newarr)
Output:
Program:
Split 2-D Array Along Columns (Axis = 1)
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
newarr = np.array_split(arr, 3, axis=1)
print(newarr)
Output:
Program:
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
newarr = np.hsplit(arr, 3)
print(newarr)