NumPy split() function is used to split an array into more than one sub-arrays.
numpy.split(arr, indices, axis=0)
arr
parameter refers to Numpy array that we want to split.
indices
parameter can be integer value or 1-D sorted Numpy integer array. If the value of indices is an integer(N) then array will be divided into N equal sub-arrays. If the value of indices is 1-D sorted integer array then array is divided as per sorted integer. For eg:
indices is [3, 4] & axis is 0 then splitting will be like this-
arr[:3], arr[3:4], and arr[4:]
axis
parameter is used to specify the axis along which you want to split array.
Note: np.split()
function returns a list of sub-arrays.
import numpy as np x = np.array([1, 2, 3, 4]) subx = np.split(x, 2) print('Splitting of array x:\n', subx) print('Accessing 0th element of sub-array:', subx[0]) y = np.array([21, 8, 42, 95, 76, 35]) suby = np.split(y, [2, 3]) print('Splitting of array y:\n', suby) print('Accessing 2nd element of sub-array:', suby[2])
Output of the above program
Splitting of array x: [array([1, 2]), array([3, 4])] Accessing 0th element of sub-array: [1 2] Splitting of array y: [array([21, 8]), array([42]), array([95, 76, 35])] Accessing 2nd element of sub-array: [95 76 35]
The code np.split(x, 2)
has splitted Numpy array x into two equal sub-arrays- [1, 2] and [3, 4]
The code np.split(y, [2, 3])
has splitted array y into three sub-arrays- y[:2], y[2:3] and y[3:]
import numpy as np x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) print('Splitting array into 2 equal parts along axis=0:\n', np.split(x, 2, axis=0)) print('Splitting array into 5 equal parts along axis=1:\n', np.split(x, 5, axis=1))
Output of the above program
Splitting array into 2 equal parts along axis=0: [array([[1, 2, 3, 4, 5]]), array([[ 6, 7, 8, 9, 10]])] Splitting array into 5 equal parts along axis=1: [array([[1], [6]]), array([[2], [7]]), array([[3], [8]]), array([[4], [9]]), array([[ 5], [10]])]
The code np.split(x, 2, axis=0)
has splitted Numpy array x into two equal sub-arrays- [[1, 2, 3, 4, 5]] and [[ 6, 7, 8, 9, 10]]
The code np.split(x, 5, axis=1)
has splitted array x into five equal sub-arrays- [[1], [6]]
, [[2], [7]]
, [[3], [8]]
, [[4], [9]]
and [[5], [10]]