Python 如何检查 nan 和空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49912730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:17:43  来源:igfitidea点击:

How to check for nan and empty string

pythonstringnan

提问by MLKing

I am trying to find all NaNsand empty strings (i.e "") in a Python list of strings. Please see the following code with 3 options:

我正在尝试NaNs在 Python 字符串列表中查找所有字符串和空字符串(即“”)。请参阅以下代码,其中包含 3 个选项:

names=['Pat','Sam', np.nan, 'Tom', '']
for idx,name in enumerate(names):
    if name=='':        #Option 1 
    if pd.isnull(name): #Option 2
    if np.isnan(name):  #Option 3 
        print(idx)

Option 1: This check, name="", doesn't catch NaN

选项 1:此检查,name="",不捕获 NaN

Option 2: This check, pd.isnull(name) doesn't catch the empty string

选项 2:此检查,pd.isnull(name) 不捕获空字符串

Option 3: This check, np.isnan(name) gives the following error on the strings (e.g "Pat").

选项 3:此检查 np.isnan(name) 在字符串上给出以下错误(例如“Pat”)。

----> 6 if np.isnan(name):

----> 6 如果 np.isnan(name):

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe*''*

类型错误:输入类型不支持 ufunc 'isnan',并且无法根据转换规则 ''safe*''* 将输入安全地强制转换为任何受支持的类型

Question: Is there any function/method that can check for empty strings, NaNs and does not give an error when it encounters a string?

问题:有没有什么函数/方法可以检查空字符串NaNs,遇到字符串不报错?

回答by juanpa.arrivillaga

Just use both:

只需使用两者

>>> names=['Pat','Sam', np.nan, 'Tom', '']
>>> for idx,name in enumerate(names):
...     if name == '' or pd.isnull(name):
...         print(idx)
...
2
4

However, realize that:

但是,要意识到:

>>> pd.isnull(None)
True

So if you want to check specifically for NaNand not None, use math.isnan(while guarding against passing non-floatvalues to math.isnan:

因此,如果您想专门NaN检查and not None,请使用math.isnan(同时防止将非float值传递给math.isnan

>>> import math
>>> for idx,name in enumerate(names):
...     if name == '' or (isinstance(name, float) and  math.isnan(name)):
...         print(idx)
...
2
4

回答by Bryan

There is a way to combine options #1 and #2 and get the result you are looking for:

有一种方法可以组合选项 #1 和 #2 并获得您正在寻找的结果:

names = ['Pat', 'Sam', np.nan, 'Tom', '']
for idx, name in enumerate(names):
    if not name or pd.isnull(name):
        print(idx)