w3resource

Swapping the first and last rows of a 4x4 array using NumPy

NumPy: Advanced Exercise-29 with Solution

Write a NumPy program to create a 4x4 array with random values and swap the first and last rows.

This NumPy program generates a 4x4 array filled with random values and swaps the first and last rows. Swapping involves exchanging the elements of the first row with the corresponding elements in the last row, effectively changing their positions within the array while maintaining the array's shape.

Sample Solution:

Python Code:

import numpy as np

# Create a 4x4 array with random values
array = np.random.random((4, 4))

# Print the original array
print("Original Array:\n", array)

# Swap the first and last rows
array[[0, -1]] = array[[-1, 0]]

# Print the array after swapping the first and last rows
print("Array after swapping first and last rows:\n", array)

Output:

Original Array:
 [[0.41772175 0.17423332 0.84823004 0.49858211]
 [0.83953919 0.01675973 0.77212078 0.01691815]
 [0.66812958 0.78669052 0.69903612 0.97760875]
 [0.39448254 0.80465228 0.90358789 0.76704065]]
Array after swapping first and last rows:
 [[0.39448254 0.80465228 0.90358789 0.76704065]
 [0.83953919 0.01675973 0.77212078 0.01691815]
 [0.66812958 0.78669052 0.69903612 0.97760875]
 [0.41772175 0.17423332 0.84823004 0.49858211]]

Explanation:

  • Import NumPy: Import the NumPy library to work with arrays.?
  • Create a Random 4x4 Array: Generate a 4x4 array filled with random values using np.random.random.
  • Print the Original Array: Print the original 4x4 array for reference.
  • Swap the First and Last Rows: Use array indexing to swap the first row (index 0) with the last row (index -1).
  • Print the Modified Array: Print the array after swapping the first and last rows.

Python-Numpy Code Editor:

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

Previous: Creating a 3x3 array and computing Cholesky Decomposition using NumPy.
Next: Rotating a 4x4 array 90 degrees Counterclockwise using NumPy.

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://www.w3resource.com/python-exercises/numpy/advanced-numpy-exercise-29.php