The NumPy split() method splits an array into multiple sub-arrays.
split() Syntax
The syntax of split() is:
numpy.split(array, indices_or_sections, axis = 0)
split() Arguments
The split() method takes the following arguments:
array- the array to splitindices- defines indices (asintor1-D array) in which the array is splitaxis(optional) - axis along which the array is to be split
Notes:
- If
indicesare an integer(N), the array is divided into N equal parts.- If N equal divisions are not possible, an error is raised.
- If
indicesis a 1-D array, the entries indicate the indices where the input array is divided.
split() Return Value
The split() method returns the list of sub-arrays.
Example 1: Split an Array into Three Arrays
Output
[array([[1, 2]]), array([[3, 4]]), array([[5, 6]])]
Example 2: Split an Array by Index
Output
[array([1, 2]), array([3, 4, 5]), array([6]), array([], dtype=int64)]
When an index exceeds the dimension of the array, the function returns an empty subarray.
Example 3: Split an Array Across Different Axes
The third parameter is used to split NumPy arrays across different axes. By default, axis is set to 0 (column-wise).
Output
Split array column-wise:
[array([[[1, 2],
[3, 4]]]), array([[[5, 6],
[7, 8]]])]
Split array row-wise:
[array([[[1, 2]],
[[5, 6]]]), array([[[3, 4]],
[[7, 8]]])]
Split array depth-wise:
[array([[[1],
[3]],
[[5],
[7]]]), array([[[2],
[4]],
[[6],
[8]]])]
>
Example 4: Split an Array into Uneven Sub-arrays
The split() function cannot split an array into uneven arrays.
Output
ERROR! raise ValueError( ValueError: array split does not result in an equal division
To split an array into unequal subarrays, you can use array_split() instead. Let's see an example.
Output
[[1 2] [3 4]] [[5 6]]
Related Methods
We can also split an array along different axes using the following methods:
- NumPy
hsplit()- split an array into multiple sub-arrays horizontally - NumPy
vsplit()- split an array into multiple sub-arrays vertically - NumPy
dsplit()- split an array into multiple sub-arrays along the 3rd axis (depth)
Let's see an example.
Output
Split array column-wise: [[[1 2] [3 4]]] [[[5 6] [7 8]]] Split array row-wise: [[[1 2]] [[5 6]]] [[[3 4]] [[7 8]]] Split array depth-wise: [[[1] [3]] [[5] [7]]] [[[2] [4]] [[6] [8]]]