w3resource

NumPy: Swap columns in a given array

NumPy: Array Object Exercise-150 with Solution

Write a NumPy program to swap columns in a given array.

Sample Solution:

Python Code:

import numpy as np
my_array = np.arange(12).reshape(3, 4)
print("Original array:")
print(my_array)
my_array[:,[0, 1]] = my_array[:,[1, 0]]
print("\nAfter swapping arrays:")
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]]

Pictorial Presentation:

NumPy: Swap columns in a given array

Python Code Editor:

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

Previous: Write a NumPy program to find elements within range from a given array of numbers.
Next: Write a NumPy program to get the row numbers in given array where at least one item is larger than a specified value.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}