You must know about how to join or append two or more arrays into a single array. Splitting a Numpy array is just the opposite of it. Here you have to use the numpy split() method. In this entire tutorial of “How to,” you will learn how to Split a Numpy Array for both dimensions 1D and 2D -Numpy array.
Splitting a 1 D Numpy array
In this section, you will learn how to split a one dimension numpy array with various examples.
Execute the following steps to split a numpy array.
Step 1: Import the necessary library
I am using only the numpy array so only import this module.
import numpy as np
Step 2: Create a One Dimensional Array
The creation of a Numpy array requires the array() method, use it.
array_1d = np.array([10,20,30,40,50,60]) array_1d
Step 3: Split the Array
You can split the array as many parts you want using the split() method. Let’s say I want to split the array into 3 and 4 Parts. then I will pass the 3 and 4 value as the argument inside the split() method.
#split the array into 3 parts np.array_split(array_1d,3)
#split the array into 4 parts np.array_split(array_1d,4)
#print each array print(split_array) print(split_array) print(split_array)
Splitting a 2 D Numpy array
Unlike 1-D Numpy array there are other ways to split the 2D numpy array. Here you have to take care of which way to split the array that is row-wise or column-wise. Let’s create a 2-D numpy array and split it.
Execute the following steps
Step 1 : Create a 2D Numpy array.
array_2d = np.array([[10,20,30],[40,50,60],[70,80,90],[100,110,120],[130,140,150]]) array_2d
Step 2: Split the array
There are two ways to split the array one is row-wise and the other is column-wise. By default, the array is split in row-wise (axis =0 ). If you want to split the array in column-wise use axis =1.
Row Wise Split
np.array_split(array_2d,2) #or np.array_split(array_2d,2,axis=0)
The above code will split the given array into two 2-D arrays. In the same, you can split the array into 3 parts passing value in split() method to 3.
Colum Wise Split
Here I am only passing the axis =1 to split the 3D array through column-wise. The output of the code is given below.
These are the ways to split the numpy array for both One and two-dimension. Hope you have understood it. If you have any query then comment below or personally contact us.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.