w3resource

NumPy: Rearrange the dimensions of a given array

NumPy: Array Object Exercise-126 with Solution

Write a NumPy program to rearrange the dimensions of a given array.

Sample Solution:

Python Code:

import numpy as np    
x = np.arange(24).reshape((6,4))
print("Original arrays:")
print(x)
new_array = np.transpose(x)
print("After reverse the dimensions:")
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]]

Pictorial Presentation:

Python NumPy: Rearrange the dimensions of a given array

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to broadcast on different shapes of arrays where a(,3) + b(3).
Next: Write a NumPy program to stack arrays in sequence horizontally (column wise).

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}