How to access split arrays in Numpy

Overview

In python, an array is a data structure used to store multiple items of the same type together. They are helpful when dealing with many values of the same data type. An array needs to import the array module for explicit declaration.

Method

The numpy.array_split() method in python is simply used to split an array into multiple sub-arrays of equal size. It takes these parameters:

  • ary: This represents the input array. This parameter is required.
  • indices_or_section: This represents the number of splits to be returned. This parameter is required.
  • axis: This is the axis along which the values are appended. This parameter is optional.

In this shot, we want to see how we can easily access the newly split arrays using their index position.

Code

import numpy as np
array1 = np.array([1, 2, 3, 4])
# splitting the array into three
new_array1 = np.array_split(array1, 3)
print('The split arrays are:', new_array1)
# to access the first split array
print('The first split array is:', new_array1[0])
# to access the second split array
print('The second split array is: ', new_array1[1])
# to access the second split array
print('The third split array is: ', new_array1[2])

Explanation

  • Line 1: we imported the numpy module
  • Line 3: we created an array, array1, using the numpy.array() method
  • Line 5: we split the created array into three using the numpy.array_split() method and assigned it to a variable called new_array1
  • Line 6: we printed the newly split array new_array1
  • Line 9: we returned the first array present in the newly split arrays
  • Line 11: we returned the second array present in the newly split arrays
  • Line 13: we returned the third array present in the newly split arrays

Free Resources