w3resource

NumPy: Rearrange the dimensions of a given array


Rearrange Array Dimensions

Write a NumPy program to rearrange array dimensions.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' with elements from 0 to 23 using np.arange() and reshaping it to a 6x4 array
x = np.arange(24).reshape((6, 4))

# Printing a message indicating the original array will be displayed
print("Original array:")
print(x)  # Displaying the original 6x4 array 'x'

# Transposing the array 'x' to reverse its dimensions using np.transpose()
new_array = np.transpose(x)

# Printing a message indicating the array after reversing the dimensions will be displayed
print("After reversing the dimensions:")

# Displaying the transposed array 'new_array'
print(new_array) 

Sample Output:

Original arrays:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
After reverse the dimensions:
[[ 0  4  8 12 16 20]
 [ 1  5  9 13 17 21]
 [ 2  6 10 14 18 22]
 [ 3  7 11 15 19 23]]

Explanation:

x = np.arange(24).reshape((6,4)): This line creates an array with values from 0 to 23 (24 values) using np.arange(24), and then reshapes it into a 6x4 array using reshape((6,4)).

new_array = np.transpose(x): It transposes the 6x4 x array by swapping its rows and columns

Finally, printf() prints the transposed new_array.

Pictorial Presentation:

Python NumPy: Rearrange the dimensions of a given array

Python-Numpy Code Editor: