Home > Net >  How to eliminate the rows from an array which have common elements at different index position in py
How to eliminate the rows from an array which have common elements at different index position in py

Time:10-30

I have a 2D array of form

[[ 1  6]
 [ 2  7]
 [ 5  6]
 [ 6  1]
 [ 6  5]
 [ 7  2]]

I want the output of the form

[[ 1  6]
 [ 2  7]
 [ 5  6]]

How I can get this output?

CodePudding user response:

Here's a solution using plain Python, but I'm sure there's a more idiomatic way with NumPy.

import numpy as np

a = np.array([
    [1, 6],
    [2, 7],
    [5, 6],
    [6, 1],
    [6, 5],
    [7, 2]])

seen = set()
out = []
for row in a:
    elements = frozenset(row)
    if elements not in seen:
        seen.add(elements)
        out.append(row)
print(np.array(out))

Output:

[[1 6]
 [2 7]
 [5 6]]
  • Related