Pandas pd.isnull()函数

时间:2016-07-14 19:48:12

标签: python pandas

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

这是我的数据框:

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

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

2 个答案:

答案 0 :(得分:5)

只是做:

mydf = mydf.notnull() * 1
mydf

enter image description here

为了完整性

mydf.isnull() * 1

enter image description here

答案 1 :(得分:2)

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

您要么将mask功能与pd.isnull

一起使用
mydf.mask(pd.isnull(mydf), 0, inplace=True)

或者您想where使用pd.notnull

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

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

相关问题