Home > Back-end >  I need to remove every point that has the same Y coordinate in an array
I need to remove every point that has the same Y coordinate in an array

Time:01-19

Basically I have an array list [x,y] that goes : [0,1][1,2][2,4][3,1][4,3] and the list goes on. I want to execute a code that removes the points that have the same y coordinate except the first one in order. I would like to have as output : [0,1][1,2][2,4][4,3]. How can I do this I have tried using np.unique but I can't mange to keep the first appearance or to remove based on the y coordinate.

Thanks

CodePudding user response:

You can use HYRY's solution from numpy.unique with order preserved, you just need to select the Y column.

import numpy as np

a = np.array([[0,1], [1,2], [2,4], [3,1], [4,3]])

_, idx = np.unique(a[:, 1], return_index=True)
a[np.sort(idx)]

result:

[[0 1]
 [1 2]
 [2 4]
 [4 3]]

CodePudding user response:

array = [[0,1],[1,2],[2,4],[3,1],[4,3]]

occured = set()
result = []
for element in array:
    if element[1] not in occured:
        result.append(element)
    occured.add(element[1])
array.clear()
array.extend(result)
print(array)
>> [[0, 1], [1, 2], [2, 4], [4, 3]]
  •  Tags:  
  • Related