pandas 熊猫 pd.isnull() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38383037/
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 01:35:33  来源:igfitidea点击:

Pandas pd.isnull() function

pythonpandas

提问by Rtut

I need to replace not null values in my dataframe with 1 and null values with 0.

我需要将数据框中的非空值替换为 1,将空值替换为 0。

Here is my dataframe:

这是我的数据框:

my_list= [['a','b','c'],['test1','test2',None],[None,'101','000']]

mydf= pd.DataFrame(my_list,columns=['col1','col2','col3'])

mydf

    col1   col2  col3
0      a      b     c
1  test1  test2  None
2   None    101   000

mydf.where((pd.isnull(mydf)),0,inplace=True)

mydf

   col1 col2  col3
0     0    0     0
1     0    0  None
2  None    0     0

I am not sure why it is replacing not null values with zero. pd.notnull() does the opposite. Can anyone explain what I am missing here?

我不确定为什么它用零替换非空值。pd.notnull() 正好相反。谁能解释我在这里缺少什么?

回答by piRSquared

Just do:

做就是了:

mydf = mydf.notnull() * 1
mydf

enter image description here

在此处输入图片说明

For completeness

为了完整性

mydf.isnull() * 1

enter image description here

在此处输入图片说明

回答by root

This is the expected behavior for where. According to the docs, wherekeeps values that are Trueand replaces values that are False, and pd.isnullwill return Trueonly for the Noneentries, which is why they were the only ones that were kept.

这是 的预期行为where。根据文档,where保留是的值True并替换是的值False,并且pd.isnullTrue仅返回None条目,这就是为什么它们是唯一保留的值。

You either want to use the maskfunction with pd.isnull:

您要么想使用该mask功能pd.isnull

mydf.mask(pd.isnull(mydf), 0, inplace=True)

Or you want to use wherewith pd.notnull:

或者你想使用wherepd.notnull

mydf.where(pd.notnull(mydf), 0, inplace=True)

Regardless, @piRSquared's method is probably better than either of the above.

无论如何,@piRSquared 的方法可能比上述任何一种方法都要好。