0

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • You could use `pandas` with `drop_duplicates`. – hilberts_drinking_problem Jan 19 '22 at 02:29
  • Please [edit] to add in the actual array. What you've written here is not valid, and it's kinda hard to tell if you're talking about a list or a NumPy array, but I assume it's an array so I added the [tag:numpy] tag for you. BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Jan 19 '22 at 02:34

2 Answers2

0
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]]
govordovsky
  • 359
  • 2
  • 17
0

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]]
wjandrea
  • 28,235
  • 9
  • 60
  • 81