Home > other >  How to delete elements repeated in a 2_D numpy array?
How to delete elements repeated in a 2_D numpy array?

Time:01-25

I have the following question which I want to solve with numpy Library. Let's suppose that we have this 'a' array

a = np.vstack(([10, 10, 20, 20, 30, 10, 40, 50, 20] ,[10, 20, 10, 20, 30, 10, 40, 50, 20]))

As output we have

[[10 10 20 20 30 10 40 50 20]
 [10 20 10 20 30 10 40 50 20]]
with the shape (2, 9)

I want to delete the elements repeated vertically in our array so that I have as result:

[[10 10 20 20 30 40 50]
 [10 20 10 20 30 40 50]]

In this example I want to delete the elements ((0, 5), (1, 5)) and ((0, 8), (1, 8)). Is there any numpy function that can do the job ? Thanks

CodePudding user response:

Following the idea of this answer, you could do the following.

np.hstack({tuple(row) for row in a.T}).T

CodePudding user response:

This is easily done with:

np.unique(a, axis=1)
  •  Tags:  
  • Related