How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0

后端 未结 9 939
轻奢々
轻奢々 2021-02-01 18:07

I have a dataframe with 71 columns and 30597 rows. I want to replace all non-nan entries with 1 and the nan values with 0.

Initially I tried for-loop on each value of th

9条回答
  •  星月不相逢
    2021-02-01 18:53

    Use notnull with casting boolean to int by astype:

    print ((df.notnull()).astype('int'))
    

    Sample:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'a': [np.nan, 4, np.nan], 'b': [1,np.nan,3]})
    print (df)
         a    b
    0  NaN  1.0
    1  4.0  NaN
    2  NaN  3.0
    
    print (df.notnull())
           a      b
    0  False   True
    1   True  False
    2  False   True
    
    print ((df.notnull()).astype('int'))
       a  b
    0  0  1
    1  1  0
    2  0  1
    

提交回复
热议问题