DEV Community

TechPlygrnd
TechPlygrnd

Posted on

NumPy Tutorial #10: Array Split

Let say If I have an array and I want to split it into two arrays, how can I do that?

Split

In NumPy, we have a method named split to divide an array into multiple arrays. The method requires two arguments, which are the original array, and the number of arrays will be generated. Let see how you can implement it.

Let us create an array

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Enter fullscreen mode Exit fullscreen mode

Then, let us create a new variable in which that hold the value of splitted array. Also, print the new variable to see the value

new_arr = np.array_split(arr, 2)

print(new_arr)
Enter fullscreen mode Exit fullscreen mode

You will get the following result

[array([1, 2, 3, 4, 5]), array([ 6,  7,  8,  9, 10])]
Enter fullscreen mode Exit fullscreen mode

You can get each individual arrays by typing the following

print(new_arr[0])
print(new_arr[1])
Enter fullscreen mode Exit fullscreen mode

You will get the following output

[1 2 3 4 5]
[ 6  7  8  9 10]
Enter fullscreen mode Exit fullscreen mode

There you go, that is how you can split an array into multiple arrays in NumPy. Thank you for reading, and have a nice day!

Top comments (0)