JFerro
JFerro

Reputation: 3433

pandas unique values with condition

I am working with a pandas DataFrame and I need to loop trough the unique values of a column. Such columns might contain values that i dont want to loop through, for instance ''

normally I do:

edges = [edge for edge in estados['EDGE'].unique() if edge != '']
for edge in edges:
    pass

my question is if there is a more pandonic way to build up the list different than the conprehension list.

like:

estados['EDGE'].unique().exclude('')

THANKS

Note: I looked for solutions like in: nunique excluding some values in pandas Python pandas unique value ignoring NaN but these solutions are even less concise as mine.

Upvotes: 0

Views: 4290

Answers (2)

Ch3steR
Ch3steR

Reputation: 20669

You can use pd.Series.mask with pd.Series.dropna and pd.Series.unique

m = estados['EDGE']==''
estados['EDGE'].mask(m).dropna().unique()

Or with pd.Series.notna

m = (estados['EDGE']!='') & (estados['EDGE'].notna())

estados['EDGE'][m]

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34046

You can use NOT operator ~:

estados[~estados['EDGE'] == '']['EDGE'].dropna().unique()

OR Use .ne:

estados[estados['EDGE'].ne('')]['EDGE'].dropna().unique()

Upvotes: 1

Related Questions