NumPy split()

Summary: in this tutorial, you’ll learn how to use the NumPy split() function to split an array into multiple sub-arrays.

Introduction to the NumPy split() function

The split() funciton splits an array into multiple sub-arrays as views. The syntax of the split() function is as follows:

numpy.split(ary, indices_or_sections, axis=0)Code language: Python (python)

In this syntax:

ary is the array to be split into subarrays.

indices_or_sections can be an integer or a 1-D array of sorted integers.

If it is an integer, the function splits the input array into N equal arrays along the axis. If the split is not possible, the function will raise an error.

If indices_or_sections is a 1D array of sorted integers, the indices indicate where along the axis the function splits the array.

When an index exceeds the dimension of the array along the axis, the function returns an empty subarray.

The following picture shows how the split() function splits the array with indices 2, 3, and 4. It results in 4 arrays.

NumPy split() function example

Let’s take some examples of using the split() function.

1) Using the split() function to split a 1D array

The following example uses the split() function to split a 1D array with seven elements into three sub-arrays:

import numpy as np


a = np.arange(1,7)
results = np.split(a,3)

print(a)
print(results)Code language: Python (python)

Output:

[1 2 3 4 5 6]
[array([1, 2]), array([3, 4]), array([5, 6])]Code language: Python (python)

The following example raises an error because the split is not possible:

import numpy as np


a = np.arange(1,7)
results = np.split(a,4)Code language: Python (python)

Output:

ValueError: array split does not result in an equal divisionCode language: Python (python)

In this example, the array has 6 elements therefore it cannot be split into 4 arrays of equal size. If you want to have a more flexible split, you can use the array_split() function.

2) Using the split() function to split a 2D array

The following example uses the split() function to split a 2D array into two subarrays:

import numpy as np

a = np.array([[1,2],[3,4],[5,6],[7,8]])
results = np.split(a,2)

print(a)
print(results)Code language: Python (python)

Output:

[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[array([[1, 2],
       [3, 4]]), array([[5, 6],
       [7, 8]])]Code language: Python (python)

3) Using the NumPy split() function using indices

The following example uses the split() function to split a 1D array using an array of indices:

import numpy as np


a = np.arange(10,70,10)
results = np.split(a, [2, 3, 4])
print(a)
print(results)Code language: Python (python)

Output:

[1 2 3 4 5 6]
[array([1, 2]), array([3]), array([4, 5, 6])]Code language: Python (python)

Summary

  • Use NumPy split() function to split an array into subarrays.
Did you find this tutorial helpful ?