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
How to check for nan and empty string
提问by MLKing
I am trying to find all NaNs
and 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, NaN
s and does not give an error when it encounters a string?
问题:有没有什么函数/方法可以检查空字符串NaN
s,遇到字符串不报错?
回答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 NaN
and not None
, use math.isnan
(while guarding against passing non-float
values 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)