Home > other >  Using Numpy to write a function that returns all rows of A that have completely distinct entries
Using Numpy to write a function that returns all rows of A that have completely distinct entries

Time:10-25

For example: For

A = np.array([
    [1, 2, 3],
    [4, 4, 4],
    [5, 6, 6]])

I want to get the output array([[1, 2, 3]]). For A = np.arange(9).reshape(3, 3), I want to get

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

WITHOUT using loops

CodePudding user response:

You can use:

B = np.sort(A, axis=1)

out = A[(B[:,:-1] != B[:, 1:]).all(1)]

Or using pandas:

import pandas as pd

out = A[pd.DataFrame(A).nunique(axis=1).eq(A.shape[1])]

Output:

array([[1, 2, 3]])
  • Related