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
Pandas pd.isnull() function
提问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 root
This is the expected behavior for where
. According to the docs, where
keeps values that are True
and replaces values that are False
, and pd.isnull
will return True
only for the None
entries, which is why they were the only ones that were kept.
这是 的预期行为where
。根据文档,where
保留是的值True
并替换是的值False
,并且pd.isnull
将True
仅返回None
条目,这就是为什么它们是唯一保留的值。
You either want to use the mask
function with pd.isnull
:
您要么想使用该mask
功能pd.isnull
:
mydf.mask(pd.isnull(mydf), 0, inplace=True)
Or you want to use where
with pd.notnull
:
或者你想使用where
同pd.notnull
:
mydf.where(pd.notnull(mydf), 0, inplace=True)
Regardless, @piRSquared's method is probably better than either of the above.
无论如何,@piRSquared 的方法可能比上述任何一种方法都要好。