我有一个字符串列表。
x = ['A', 'B', nan, 'D']
并想要移除NaN。
我尝试过:
x = x[~numpy.isnan(x)]
但这仅适用于包含数字的情况。在Python 3+中,我们如何解决字符串的问题?
x = ['A', 'B', nan, 'D']
并想要移除NaN。
我尝试过:
x = x[~numpy.isnan(x)]
但这仅适用于包含数字的情况。在Python 3+中,我们如何解决字符串的问题?
如果您有一个numpy数组,您可以简单地检查该项不是字符串nan
,但如果您有一个列表,您可以使用is
和np.nan
来检查其身份,因为它是单例对象。
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']
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']
[i for i in x if not i in ['nan', np.nan]]
,否则加1 - Colonel Beauvelnp.nan
是否有特殊之处吗? - Mazdaknp.nan
只是一些浮点常量。出于同样的原因,您也不会比较is math.pi
。 - Josh Leemath.isnan
和一个简单的列表推导式。import math
x = [y for y in x if not math.isnan(y)]
math.isnan('A')
吗?在 OP 的 x
上测试了吗? - hpauljnp.nan
,而应该使用None
;但是如果您确实有nan
,可以这样做:import numpy as np
[i for i in x if i is not np.nan]
# ['A', 'B', 'D']
nan
可能更好,因为nan
会被转换为字符串nan
,但None
仍然保持为None
。 - Psidomis
进行比较,这将会失败。 - Josh Lee
[s for s in x if str(s) != 'nan']
str
:[s for s in map(str, x) if s != 'nan']
['A', 'B', 'D']
。
non
对象。我将其更改为numpy,以便未来的提问者可以轻松找到该问题。 - Mazdak