Best Way to Split a Numpy Array , Know in 2 Steps Only

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
1 D Numpy Array Creation

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)
Splitting the Numpy Array in 3 and 4 Sub Arrays
You can also access the subpart of the array in the same way as you access the simple array.
#print each array
print(split_array[0])
print(split_array[1])
print(split_array[2])
Displaying Each 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
2 D Numpy Array Creation

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)
Splitting the 2D Numpy Array RowWise

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

np.array_split(array_2d,2,axis=1)
np.array_split(array_2d,3,axis=1)

Here I am only passing the axis =1 to split the 3D array through column-wise. The output of the code is given below.

Splitting the 2D Numpy Array Column Wise

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.

Source:

Official Split Numpy Documentation