Remove NaN value from a set

In practice, you could look at the fact that nan != nan as a feature, not a bug:

>>> a = {float('nan'), float('nan'), 'a'}
>>> a
{nan, nan, 'a'}
>>> {x for x in a if x==x}
{'a'}

On the positive side, no need for a helper function. On the negative side, if you have a non-nan object which is also not equal to itself, you'll remove that too.


Also you can use filter:

In[75]: a = set((float('nan'), float('nan'), 'a'))

In[76]: set(filter(lambda x: x == x , a))
Out[76]: {'a'}

Use pd.notna() from pandas, e.g.:

In [219]: import pandas as pd

In [220]: a = set((float('nan'), float('nan'), 'a'))

In [221]: a = {x for x in a if pd.notna(x)}

In [222]: a
Out[222]: {'a'}

Tags:

Python