NumPy: Create a new array from a given array, swapping first and last, second and third columns
NumPy: Basic Exercise-57 with Solution
Write a NumPy program to create a 4x4 array. Create an array from said array by swapping first and last, second and third columns.
Create the array using numpy.arange which returns evenly spaced values within a given interval.
Sample Solution:
Python Code:
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'nums' with values from 0 to 15 and reshaping it to a 4x4 matrix
nums = np.arange(16, dtype='int').reshape(-1, 4)
# Printing a message indicating the original array 'nums'
print("Original array:")
print(nums)
# Creating a new array 'new_nums' by swapping the first and last columns of the 'nums' array
# This is done by using slicing with a step of -1 to reverse the column order
new_nums = nums[:, ::-1]
# Printing a message indicating the new array after swapping the first and last columns
print("\nNew array after swapping first and last columns of the said array:")
print(new_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 columns of the said array: [[ 3 2 1 0] [ 7 6 5 4] [11 10 9 8] [15 14 13 12]]
Explanation:
In the above code -
np.arange(16, dtype='int').reshape(-1, 4) creates a 2D NumPy array of shape (4, 4) with integer values from 0 to 15, inclusive. The -1 in the reshape() function is used to automatically calculate the appropriate number of rows based on the specified number of columns (4).
nums[:, ::-1]: The slice operation [::-1] is applied to the columns, effectively reversing their order.
Python-Numpy Code Editor:
Previous: NumPy program to create a three-dimension array with shape (3,5,4) and set to a variable.
Next: NumPy program to swap rows and columns of a given array in reverse order.
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