Member-only story
Hi everyone, welcome back. NumPy is a library for the Python programming language. NumPy is short for “Numerical Python” and is a popular library used for data science purposes. NumPy is used specifically to work with arrays as it provides various functions and support. In this tutorial, we will go over how we can split NumPy arrays by using some of the functions that NumPy provides. With this introduction out of the way, let’s get into it.
Array Split
We can use the array_split() function to split our array and we can specify how many splits we want. Let’s see an example:
import numpy as np
array = np.array([1, 2, 3])
splitArray = np.array_split(array, 3)
print(splitArray)Output:
[array([1]), array([2]), array([3])]
In this example, we told the array_split() function to split our original array by 3. As we can see in the output, the result of the array split left us with 3 new arrays, containing one element each.
Let’s see an example of what it would look like if there are an uneven amount of elements that can go in each new array:
import numpy as np
array = np.array([1, 2, 3, 4, 5])
splitArray = np.array_split(array, 3)
print(splitArray)Output:
[array([1, 2]), array([3, 4]), array([5])]