w3resource

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

NumPy: Array Object Exercise-62 with Solution

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:

Previous: Write a NumPy program to split an array of 14 elements into 3 arrays, each of which has 2, 4, and 8 elements in the original order.
Next: Write a NumPy program to get the number of nonzero elements in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-62.php