NumPy: Swap columns in a given array
Swap Columns in 2D Array
Write a NumPy program to swap columns in a given array.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating a NumPy array 'my_array' with elements from 0 to 11, reshaped into a 3x4 matrix
my_array = np.arange(12).reshape(3, 4)
# Displaying a message indicating the original array will be printed
print("Original array:")
# Printing the original array 'my_array'
print(my_array)
# Swapping columns 0 and 1 of the array using NumPy indexing
my_array[:, [0, 1]] = my_array[:, [1, 0]]
# Displaying a message indicating the array after swapping will be printed
print("\nAfter swapping arrays:")
# Printing the array after swapping columns 0 and 1
print(my_array)
Sample Output:
Original array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] After swapping arrays: [[ 1 0 2 3] [ 5 4 6 7] [ 9 8 10 11]]
Explanation:
In the above exercise -
my_array = np.arange(12).reshape(3, 4): This line creates a 2-dimensional NumPy array called my_array with the shape (3, 4) and elements from 0 to 11.
my_array[:,[0, 1]] = my_array[:,[1, 0]]: This line swaps the first and second columns of my_array. The part my_array[:,[0, 1]] selects the first and second columns, while my_array[:,[1, 0]] selects the second and first columns, in that order. By assigning my_array[:,[1, 0]] to my_array[:,[0, 1]], the first and second columns are effectively swapped.
Finally print() function prints the resulting ‘my_array’ after swapping the columns.
Pictorial Presentation:
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