Python Pandas: if the data is NaN, then change to be 0, else change to be 1 in data frame

后端 未结 3 700
迷失自我
迷失自我 2021-01-04 08:41

I have a DataFrame:df as following:

 row  id  name    age   url           
  1   e1   tom    NaN   http1   
  2   e2   john   25    NaN
  3   e3   lucy   NaN         


        
3条回答
  •  别那么骄傲
    2021-01-04 09:20

    Use np.where with pd.notnull to replace the missing and valid elements with 0 and 1 respectively:

    In [90]:
    df[['age', 'url']] = np.where(pd.notnull(df[['age', 'url']]), 1, 0)
    df
    
    Out[90]:
       row  id  name  age  url
    0    1  e1   tom    0    1
    1    2  e2  john    1    0
    2    3  e3  lucy    0    1
    3    4  e4  tick    1    0
    

提交回复
热议问题