NumPy Tutorial NumPy Statistics NumPy References

NumPy - split() function



The NumPy split() function splits an array into multiple sub-arrays as views into ary.

Syntax

numpy.split(ary, indices_or_sections, axis=0)

Parameters

ary Required. Specify the array (ndarray) to be divided into sub-arrays.
indices_or_sections Required. Specify indices_or_sections as int or 1-D array.
  • If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.
  • If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in:
    • ary[:2]
    • ary[2:3]
    • ary[3:]
  • If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.
axis Optional. Specify the axis along which to split. Default is 0.

Return Value

Returns a list of sub-arrays as views into ary.

Example:

In the example below, split() function is used to split a given array.

import numpy as np

Arr = np.array([[10, 20, 30],
                 [30, 40, 60],
                 [70, 80, 90]])

#splitting the array 
Arr1 = np.split(Arr, 3)

#displaying results
print("Arr is:")
print(Arr)
print("\nArr1 is:")
print(Arr1)

The output of the above code will be:

Arr is:
[[10 20 30]
 [30 40 60]
 [70 80 90]]

Arr1 is:
[array([[10, 20, 30]]), array([[30, 40, 60]]), array([[70, 80, 90]])]

Example: indices_or_sections as 1-D array

When indices_or_sections is passed as 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in: array[:2], array[2:3], array[3:].

import numpy as np

Arr = np.array([[10, 20, 30],
                 [30, 40, 60],
                 [70, 80, 90],
                 [100, 200, 300]])

#splitting the array 
Arr1 = np.split(Arr, [2,3])

#displaying results
print("Arr is:")
print(Arr)
print("\nArr1 is:")
print(Arr1)

The output of the above code will be:

Arr is:
[[ 10  20  30]
 [ 30  40  60]
 [ 70  80  90]
 [100 200 300]]

Arr1 is:
[array([[10, 20, 30],
       [30, 40, 60]]), array([[70, 80, 90]]), array([[100, 200, 300]])]

❮ NumPy - Array Manipulation