Skip to content
Related Articles

Related Articles

How to swap columns of a given NumPy array?
  • Last Updated : 26 Aug, 2020

In this article, let’s discuss how to swap columns of a given NumPy array.

Approach :

  • Import NumPy module
  • Create a NumPy array
  • Swap the column with Index
  • Print the Final array

Example 1: Swapping the column of an array. 

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing Module
import numpy as np
  
  
# creating array with shape(4,3)
my_array = np.arange(12).reshape(4, 3)
print("Original array:")
print(my_array)
  
# swapping the column with index of 
# orginal array
my_array[:, [2, 0]] = my_array[:, [0, 2]]
print("After swapping arrays the last column and first column:")
print(my_array)

chevron_right


Output :

Original array:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
After swapping arrays the last column and first column:
[[ 2  1  0]
 [ 5  4  3]
 [ 8  7  6]
 [11 10  9]]

Example 2: Swapping the column of an array with the user chooses.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing Module
import numpy as np
  
  
# Creating array
my_array = np.arange(12).reshape(4, 3)
print("Orginal Array : ")
print(my_array)
# creating function for swap
  
def Swap(arr, start_index, last_index):
    arr[:, [start_index, last_index]] = arr[:, [last_index, start_index]]
  
# passing parameter into the function
Swap(my_array, 0, 1)
print(" After Swapping :")
print(my_array)

chevron_right


Output :

Orginal Array : 
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
 After Swapping :
[[ 1  0  2]
 [ 4  3  5]
 [ 7  6  8]
 [10  9 11]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :