1.

What happens when we use the arrays_split() method for splitting the NumPy array?

Answer»

The array_split() method is similar to the split() method as it helps in splitting a given array to multiple subarrays. The main difference is that the array_split() allows sections to be an integer which does not result in equal array division. For an array of length L, if we want it to split to N subarrays, then L % N subarrays of size (L//N + 1) and remaining subarrays are of size L//N.

In the above figure, we see there are 5 elements in the array, we want to split the array to 3 subarrays. So L % N = 5%3 = 2 subarrays of size (L//N +1) = (5//3 +1) = 2 are returned and remaining 1 subarray of size L//N = 1 is returned.

Syntax:

np.array_split(array, sections, axis=0)

where,


  • array - Given Input array.

  • sections - List of indices or Number of subarrays to be returned.

  • axis - Axis along which values have to be appended.

The code for the example illustrated above is:

import numpy as np
arr = np.arange(5.0)
split_arrs = np.array_split(arr, 3)
split_arrs

Output:

[array([0., 1.]), array([2., 3.]), array([4.])]


Discussion

No Comment Found