在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:04:25  来源:igfitidea点击:

Check for None in pandas dataframe

pythonpandasnumpynan

提问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 applymapwith a lambdato check if an element is Noneas follows, (constructed a different example, as in your original one, Noneis coerced to np.nanbecause the data type is float, you will need an objecttype column to hold Noneas is, or as commented by @Evert, Noneand NaNare 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