NumPy: Create a new array from a given array swapping first and last rows
NumPy: Basic Exercise-50 with Solution
Write a NumPy program to create a 4x4 array with random values. Create an array from the said array swapping first and last rows.
Sample Solution :
Python Code :
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'nums' ranging from 0 to 15 and reshaping it into a 4x4 array
nums = np.arange(16, dtype='int').reshape(-1, 4)
# Printing a message indicating the original array
print("Original array:")
print(nums)
# Swapping the first and last rows of the 'nums' array
# nums[[0,-1],:] accesses the first and last rows, and then swaps them using advanced indexing
nums[[0,-1],:] = nums[[-1,0],:]
# Printing the array after swapping the first and last rows
print("\nNew array after swapping first and last rows of the said array:")
print(nums)
Sample Output:
Original array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] New array after swapping first and last rows of the said array: [[12 13 14 15] [ 4 5 6 7] [ 8 9 10 11] [ 0 1 2 3]]
Explanation:
In the above code -
np.arange(16, dtype='int').reshape(-1, 4) creates a 2D array of integers from 0 to 15 with a shape of 4 rows and 4 columns stores in the variable ‘nums’. The -1 in the reshape method means NumPy will automatically infer the number of rows based on the number of columns specified (4 in this case).
nums[[0,-1],:] = nums[[-1,0],:]: This line swaps the first (0-th) and last (-1-th) rows of the nums array. It uses advanced indexing to achieve this:
- nums[[0,-1],:]: Selects the first and last rows of the array.
- nums[[-1,0],:]: Selects the last and first rows of the array, in that order.
Then, the selected rows are assigned to each other, effectively swapping their positions in the array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: NumPy program to generate a uniform, non-uniform random sample from a given 1-D array with and without replacement.
Next: NumPy program to create a new array of given shape (5,6) and type, filled with zeros.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics