在 Pandas 数据框中检查 None
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45271309/
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
Check for None in pandas dataframe
提问by ConanG
I would like to find where None is found in the dataframe.
我想在数据框中找到 None 的位置。
pd.DataFrame([None,np.nan]).isnull()
OUT:
0
0 True
1 True
isnull() finds both numpy Nan and None values.
isnull() 找到 numpy Nan 和 None 值。
I only want the None values and not numpy Nan. Is there an easier way to do that without looping through the dataframe?
我只想要 None 值而不是 numpy Nan。有没有更简单的方法来做到这一点而不循环遍历数据框?
Edit: After reading the comments, I realized that in my dataframe in my work also include strings, so the None were not coerced to numpy Nan. So the answer given by Pisdom works.
编辑:阅读评论后,我意识到在我的工作中的数据框中还包含字符串,因此 None 没有被强制为 numpy Nan。所以 Pisdom 给出的答案是有效的。
回答by Psidom
You could use applymap
with a lambda
to check if an element is None
as follows, (constructed a different example, as in your original one, None
is coerced to np.nan
because the data type is float
, you will need an object
type column to hold None
as is, or as commented by @Evert, None
and NaN
are indistinguishable in numeric type columns):
你可以使用applymap
一个lambda
检查一个element is None
如下,(构建不同的例子,在你原来的,None
将强制使用np.nan
,因为数据类型float
,您将需要一个object
类型列保持None
原样,或由@Evert评论,None
并且NaN
在数字类型列中无法区分):
df = pd.DataFrame([[None, 3], ["", np.nan]])
df
# 0 1
#0 None 3.0
#1 NaN
df.applymap(lambda x: x is None)
# 0 1
#0 True False
#1 False False