Home > OS >  How can I remove one of the reverse pairs of elements from an nd numpy array without multiple for lo
How can I remove one of the reverse pairs of elements from an nd numpy array without multiple for lo

Time:09-17

For example:

original: [[0 2] [0 3] [1 4] [2 0] [2 3] [3 0] [3 2] [4 1]]

edited: [[0 2] [0 3] [1 4] [2 3]]

CodePudding user response:

One option: sort and get the unique values:

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

out = np.unique(np.sort(a), axis=0)

output:

array([[0, 2],
       [0, 3],
       [1, 4],
       [2, 3]])

If you want to ensure keeping the original (unsorted) data:

# different example, note the initial [2, 0]
a = np.array([[2, 0], [0, 3], [1, 4], [2, 0], [2, 3], [3, 0], [3, 2], [4, 1]])

idx = np.unique(np.sort(a), axis=0, return_index=True)[1]

a[idx]

output:

array([[2, 0],
       [0, 3],
       [1, 4],
       [2, 3]])

CodePudding user response:

A fast and simple way with one for loop:

s = [[0, 2], [0, 3], [1, 4], [2, 0], [2, 3], [3, 0], [3, 2], [4, 1]]
 
result = []
result.append(s[0])

for x in s:
    if not([x[-1],x[0]] in result) and not(x  in result):
        result.append(x)
result

Output:

[[0, 2], [0, 3], [1, 4], [2, 3]]
  • Related