29 Mar Split Numpy Array
Split means to break/ slash an array into multiple arrays. To split an array, use the array_split() method. The following is the syntax:
array_split(arr_name, split_num)
Here, arr_name is the name of the array, split_num is the count of splits.
In this lesson, we will learn how to,
- Split a 1D array
- Access a split 1D array
- Split a 2D array and how to access
Split a 1D array
As shown above, to split an array in Numpy, we use the array_split() method. Herein, we will split a 1D array. Let us see an example of splitting a 1D array:
import numpy as np
# Create a Numpy array
n = np.array([10, 20, 30, 40, 50, 60])
print("Iterating array...")
for a in n:
print(a)
# splitting array into 2
resarr = np.array_split(n, 2)
print("\nArray after splitting i.e. returns 2 arrays");
for a in resarr:
print(a)
Output
Iterating array... 10 20 30 40 50 60 Array after splitting i.e. returns 2 arrays [10 20 30] [40 50 60]
Access a split 1D array
To access a split One-Dimensional array, use the index number for the array element you want to display. Let us see an example to learn how to access a splitter 1D array:
import numpy as np
n = np.array([10, 20, 30, 40, 50, 60])
print("Iterating array...")
for a in n:
print(a)
# splitting into 2
resarr = np.array_split(n, 2)
print("\nArray after splitting i.e. returns 2 arrays");
print(resarr)
print("\nAccess splitted array individually...");
print("Array1 = ",resarr[0])
print("Array2 = ",resarr[1])
Output
Iterating array... 10 20 30 40 50 60 Array after splitting i.e. returns 2 arrays [array([10, 20, 30]), array([40, 50, 60])] Access splitted array individually... Array1 = [10 20 30] Array2 = [40 50 60]
Split a 2D array and access
The split result will be a 2D array, for example, if a 2D array is split into two, there will be two 2D arrays as a result. Let us see an example of splitting a 2D array:
import numpy as np
n = np.array([[1,3,5],[4,8,12]])
print("Iterating array...")
for a in n:
print(a)
# splitting into 2
resarr = np.array_split(n, 2)
print("\nArray after splitting (returns 2 arrays)");
print(resarr)
print("\nAccess splitted array individually...");
print("Array1 = ",resarr[0])
print("Array2 = ",resarr[1])
Output
Iterating array... [1 3 5] [ 4 8 12] Array after splitting (returns 2 arrays) [array([[1, 3, 5]]), array([[ 4, 8, 12]])] Access splitted array individually... Array1 = [[1 3 5]] Array2 = [[ 4 8 12]]
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments