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:

# 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

Python-Numpy Code Editor:

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-150.php