Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas pd.isnull() function

Tags:

python

pandas

I need to replace not null values in my dataframe with 1 and null values with 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?

like image 769
Rtut Avatar asked Jun 02 '26 04:06

Rtut


1 Answers

Just do:

mydf = mydf.notnull() * 1
mydf

enter image description here

For completeness

mydf.isnull() * 1

enter image description here

like image 70
piRSquared Avatar answered Jun 03 '26 19:06

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!