How to remove numpy nan from a string list in Python?

I have a list of strings

x = ['A', 'B', nan, 'D']

and want to remove nan.

I tried:

x = x[~numpy.isnan(x)]

But this only works if it contains numbers. How do we solve this for strings in Python 3+?

+4
source share
4 answers

If you have a numpy array, you can simply verify that the item is not a string nan, but if you have a list, you can verify the identity with isand np.nan, since it is a singleton object.

In [25]: x = np.array(['A', 'B', np.nan, 'D'])

In [26]: x
Out[26]: 
array(['A', 'B', 'nan', 'D'], 
      dtype='<U3')

In [27]: x[x != 'nan']
Out[27]: 
array(['A', 'B', 'D'], 
      dtype='<U3')


In [28]: x = ['A', 'B', np.nan, 'D']

In [30]: [i for i in x if i is not np.nan]
Out[30]: ['A', 'B', 'D']

Or as a functional approach, if you have a python list:

In [34]: from operator import is_not

In [35]: from functools import partial

In [37]: f = partial(is_not, np.nan)

In [38]: x = ['A', 'B', np.nan, 'D']

In [39]: list(filter(f, x))
Out[39]: ['A', 'B', 'D']
+5
source

You can use a math.isnangood old list comprehension.

- :

import math
x = [y for y in x if not math.isnan(y)]
+3

np.nan , None; nan, :

import numpy as np

[i for i in x if i is not np.nan]
# ['A', 'B', 'D']
+1

:

[s for s in x if str(s) != 'nan']

Or, convert everything to strat the beginning:

[s for s in map(str, x) if s != 'nan']

Both approaches give ['A', 'B', 'D'].

+1
source

Source: https://habr.com/ru/post/1673024/


All Articles