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.

This problem involves writing a NumPy program to swap the rows and columns of a given array in reverse order. The task requires utilizing NumPy's array manipulation capabilities, such as slicing and indexing, to efficiently perform row and column swapping operations in reverse order. By rearranging the rows and columns of the original array in reverse, the program generates a modified array with the desired row and column positions exchanged. This facilitates data reorganization for various computational and analytical tasks.

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) 

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.



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/basic/numpy-basic-exercise-58.php