ScientiaEtVeritas
ScientiaEtVeritas

Reputation: 5278

Get All Unique Values in a Row

I have a DataFrame df1 that looks like this:

A       B       C
-----------------
1       1       2
2       2       3
5       4       9

I want to get all the unique values in a row. For example 1 and 2 in the first row. 2, 3 in the second row. And 4, 5 and 9 in the third row.

Result can vary, I can imagine a new column that contains a list with unique values or replacing duplicates with None would be also okay (or something else, maybe there is something more pythonic for this case).

Upvotes: 10

Views: 16524

Answers (3)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Lets use pd.unique i.e

df.T.agg([pd.unique])

        0       1          2
unique  [1, 2]  [2, 3]  [5, 4, 9]

Upvotes: 8

BENY
BENY

Reputation: 323236

list(map(set,df.values))
Out[72]: [{1, 2}, {2, 3}, {4, 5, 9}]

Upvotes: 20

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

In [88]: df.stack().groupby(level=0).apply(lambda x: x.unique().tolist())
Out[88]:
0       [1, 2]
1       [2, 3]
2    [5, 4, 9]
dtype: object

Upvotes: 8

Related Questions