How to rearrange columns of a 2D NumPy array using given index positions?
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 packageimport numpy # create a numpy arrayarr = 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 arrayprint(arr) # declare index listi = [2,4,0,3,1] # create outputoutput = arr[:,i] # view outputprint(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]]

