Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to rearrange columns of a 2D NumPy array using given index positions?

  • Last Updated : 05 Sep, 2020

In this article, we will learn how to rearrange columns of a given numpy array using given index positions. Here the columns are rearranged with the given indexes. For this, we can simply store the columns values in lists and arrange these according to the given index list but this approach is very costly. So, using by using the concept of numpy array this can be easily done in minimum time.

Example :

Arr = [[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]] and i = [2, 4, 0, 3, 1]
then output is [[3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2]].

 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Here, i[0] = 2 i.e; 3rd column so output = [[3],[3],[3],][3],[3]].
     i[1] = 4 i.e; 5th column so output = [[3,5],[3,5],[3,5],][3,5],[3,5]].
     i[2] = 0 i.e; 1st column so output = [[3,5,1],[3,5,1],[3,5,1],][3,5,1],[3,5,1]].
     i[3] = 3 i.e; 4th column so output = [[3,5,1,4],[3,5,1,4],[3,5,1,4],][3,5,1,4],[3,5,1,4]].
     i[4] = 1 i.e; 2nd column so output = [[3,5,1,4,2],[3,5,1,4,2],[3,5,1,4,2],][3,5,1,4,2],[3,5,1,4,2]].

Below is the implementation with an example :

Python3




# importing package
import numpy
  
# create a numpy array
arr = numpy.array([[1,2,3,4,5],
                   [1,2,3,4,5],
                   [1,2,3,4,5],
                   [1,2,3,4,5],
                   [1,2,3,4,5]
                   ])
  
# view array
print(arr)
  
# declare index list
i = [2,4,0,3,1]
  
# create output
output = arr[:,i]
  
# view output
print(output)

Output :

[[1 2 3 4 5]
 [1 2 3 4 5]
 [1 2 3 4 5]
 [1 2 3 4 5]
 [1 2 3 4 5]]
[[3 5 1 4 2]
 [3 5 1 4 2]
 [3 5 1 4 2]
 [3 5 1 4 2]
 [3 5 1 4 2]]
My Personal Notes arrow_drop_up
Recommended Articles
Page :