w3resource

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:

NumPy: Swap columns in a given array

For more Practice: Solve these Related Problems:

  • Write a NumPy program to swap two specified columns in a 2D array using advanced indexing.
  • Create a function that accepts a 2D array and two column indices, then returns the array with those columns swapped.
  • Test the column swap on arrays with different data types and verify the order of elements post-swap.
  • Implement a solution that uses np.copy to avoid modifying the original array during the swap process.

Go to:


PREV : Find Elements in a Specified Range
NEXT : Get rows where elements are larger than a specified value.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.