Python

NumPy Np.array_Split()

We are back with another NumPy article. In this one, we will explore the np.array_split() function.

The array_split() function in NumPy allows us to split an array into sub-arrays of different dimensions.

Function Syntax

The syntax of the function is as shown in the code snippet below:

1
numpy.array_split(ary, indices_or_sections, axis=0)

Function Parameters

The function parameters are explained below:

  1. ary – defines the input array.
  2. indices_or_sections – determines the number of sections among which the array is split.
  3. Axis – represents along which axis the collection is divided.

The function will return the array divided into different dimensions.

Example #1

In the example below, we use the array_split method to split an array into two subarrays.

1
2
3
4
# import numpy
import numpy as np
arr = np.arange(6).reshape(2,3)
print(np.array_split(arr, 2))

The code above should result in two subarrays as shown:

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

Example #2

We can also perform the same operation on a two-dimensional array as illustrated in the code below:

1
2
arr = np.array([[1,2,3], [4,5,6], [7,8,9]])
print(np.array_split(arr, 3))

The above should return:

1
[array([[1, 2, 3]]), array([[4, 5, 6]]), array([[7, 8, 9]])]

In Closing

Using this guide, you understood how to use NumPy’s array_split() function to split an array into different dimensions.

Thanks for reading & See you in the next one!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list