w3resource

NumPy: Split of an array of shape 4x4 it into two arrays along the second axis


Split 4x4 Array Along Second Axis

Write a NumPy program that splits an array of shape 4x4 into two arrays along the second axis.
Sample array :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Pictorial Presentation:

Python NumPy: Split an of array of shape 4x4 it into two arrays along the second axis

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 4x4 NumPy array 'x' containing numbers from 0 to 15 using np.arange and reshape
x = np.arange(16).reshape((4, 4))

# Displaying the original 4x4 array 'x'
print("Original array:", x)

# Splitting the array 'x' horizontally into sub-arrays at columns 2 and 6 using np.hsplit
print("After splitting horizontally:")
print(np.hsplit(x, [2, 6])) 

Sample Output:

Original array: [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
After splitting horizontally:
[array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11],
       [14, 15]]), array([], shape=(4, 0), dtype=int64)] 

Explanation:

In the above exercise –

‘x = np.arange(16).reshape((4, 4))’ creates a 2D array x containing integers from 0 to 15 arranged in a 4x4 grid.

print(np.hsplit(x, [2, 6])): The np.hsplit() function is used to split the array x into multiple subarrays along the horizontal axis. The split indices are provided as a list [2, 6]. This means that the array ‘x’ will be split into three subarrays: from the beginning to column index 2 (exclusive), from column index 2 to column index 6 (exclusive), and from column index 6 to the end. Note that since the original array ‘x’ only has 4 columns, the third subarray will be empty.

Python-Numpy Code Editor: