w3resource

NumPy: Swap rows and columns of a given array in reverse order

NumPy: Basic Exercise-58 with Solution

Write a NumPy program to swap rows and columns of a given array in reverse order.

Sample Solution:

Python Code:

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

# Creating a NumPy array 'nums' containing a single 2D array with four rows and four columns
nums = np.array([[[1, 2, 3, 4],
               [0, 1, 3, 4],
               [90, 91, 93, 94],
               [5, 0, 3, 2]]])

# Printing a message indicating the original array 'nums'
print("Original array:")
print(nums)

# Swapping rows and columns of the 'nums' array in reverse order using slicing
# Reversing both rows and columns using [::-1, ::-1]
new_nums = nums[::-1, ::-1]

# Printing the new array after swapping rows and columns in reverse order
print("\nSwap rows and columns of the said array in reverse order:")
print(new_nums) 

Sample Output:

Original array:
[[[ 1  2  3  4]
  [ 0  1  3  4]
  [90 91 93 94]
  [ 5  0  3  2]]]

Swap rows and columns of the said array in reverse order:
[[[ 5  0  3  2]
  [90 91 93 94]
  [ 0  1  3  4]
  [ 1  2  3  4]]]
None

Explanation:

In the above code –

np.array([[[1, 2, 3, 4], [0, 1, 3, 4], [90, 91, 93, 94], [5, 0, 3, 2]]]) creates a 3D NumPy array of shape (1, 4, 4) with the specified values.

nums[::-1, ::-1]: The slice operation [::-1] is applied to both the first and second axes (rows and columns), effectively reversing their order.

Python-Numpy Code Editor:

Previous: NumPy program to create a 4x4 array, now create a new array from the said array swapping first and last, second and third columns.
Next: NumPy program to multiply two given arrays of same size element-by-element.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.