Reputation: 3433
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
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
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