NumPy: Create an array of 4,5 shape and to reverse the rows of the said array
NumPy: Array Object Exercise-177 with Solution
Write a NumPy program to create an array of 4,5 shape and to reverse the rows of the said array. After reversing 1st row will be 4th and 4th will be 1st, 2nd row will be 3rd row and 3rd row will be 2nd row.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing NumPy library
import numpy as np
# Creating a NumPy array using arange from 0 to 19 and reshaping it to a 4x5 array
array_nums = np.arange(20).reshape(4, 5)
# Printing the original array
print("Original array:")
print(array_nums)
# Reversing the order of rows in the array
print("\nAfter reversing:")
array_nums[:] = array_nums[3::-1]
print(array_nums)
Sample Output:
Original array: [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] After reversing: [[15 16 17 18 19] [10 11 12 13 14] [ 5 6 7 8 9] [ 0 1 2 3 4]]
Explanation:
In the above code -
array_nums = np.arange(20).reshape(4,5): This code creates a 1-dimensional NumPy array containing numbers from 0 to 19 and then reshapes it into a 2-dimensional array with 4 rows and 5 columns.
array_nums[:] = array_nums[3::-1]: This code reverses the order of the rows within the array. The syntax array_nums[3::-1] selects all rows in reverse order, starting from the last row (index 3) to the first row (index 0) with a step of -1. By setting array_nums[:] equal to array_nums[3::-1], we effectively reverse the order of the rows in the original array.
Python-Numpy Code Editor:
Previous: Write a NumPy program to create an array of 4,5 shape and swap column1 with column4.
Next: Write a NumPy program to replace all the nan (missing values) of a given array with the mean of another array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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/python-numpy-exercise-177.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics