Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to rearrange columns of a 2D NumPy array using given index...

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]].

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]]
RELATED ARTICLES

Most Popular

Recent Comments