How to Use np.split in NumPy: Syntax and Examples
Use
np.split(array, indices_or_sections, axis=0) to divide a NumPy array into multiple sub-arrays. The indices_or_sections parameter controls where the splits happen, and axis decides along which dimension to split.Syntax
The function np.split splits an array into multiple sub-arrays.
array: The input NumPy array to split.indices_or_sections: Either an integer or a list of sorted integers. If an integer, it divides the array into equal parts. If a list, it specifies the indices where to split.axis: The axis along which to split. Default is 0 (rows for 2D arrays).
python
np.split(array, indices_or_sections, axis=0)Example
This example shows how to split a 1D array into three equal parts and a 2D array along columns.
python
import numpy as np # 1D array split into 3 equal parts arr1 = np.arange(9) splits1 = np.split(arr1, 3) # 2D array split along columns at indices 2 and 4 arr2 = np.arange(20).reshape(4,5) splits2 = np.split(arr2, [2, 4], axis=1) print('1D array splits:') for part in splits1: print(part) print('\n2D array splits:') for part in splits2: print(part)
Output
1D array splits:
[0 1 2]
[3 4 5]
[6 7 8]
2D array splits:
[[ 0 1]
[ 5 6]
[10 11]
[15 16]]
[[ 2 3]
[ 7 8]
[12 13]
[17 18]]
[[ 4]
[ 9]
[14]
[19]]
Common Pitfalls
Common mistakes include:
- Trying to split into unequal parts with an integer number of sections, which raises an error.
- Using indices that are out of bounds or not sorted.
- Forgetting to specify
axiswhen splitting multi-dimensional arrays.
python
import numpy as np arr = np.arange(6) # Wrong: splitting into 4 equal parts when length 6 is not divisible by 4 try: np.split(arr, 4) except Exception as e: print('Error:', e) # Right: split at indices splits = np.split(arr, [2, 4]) print('Correct splits:', splits)
Output
Error: array split does not result in an equal division
Correct splits: [array([0, 1]), array([2, 3]), array([4, 5])]
Quick Reference
| Parameter | Description |
|---|---|
| array | Input array to split |
| indices_or_sections | Integer for equal parts or list of indices for split points |
| axis | Axis along which to split (default 0) |
Key Takeaways
Use np.split to divide arrays into multiple parts by specifying split points or equal sections.
If using an integer for sections, the array length must be divisible by that number.
For multi-dimensional arrays, specify the axis to split along.
Indices for splitting must be sorted and within array bounds.
np.split returns a list of sub-arrays after splitting.