NumPy: Create a new array from a given array, swapping first and last, second and third columns
Swap Columns in 4x4 Array
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.
This problem involves writing a NumPy program to create a 4x4 array. It also involves creating a new array by swapping the first and last columns, as well as the second and third columns. The task requires utilizing NumPy's array manipulation capabilities, such as array slicing and indexing, to efficiently perform the column swapping operation. By rearranging the columns of the original array, the program generates a modified array with the desired 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' 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)
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:
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