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

后端 未结 9 1044
轻奢々
轻奢々 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:47

    Here i will give a suggestion to take a particular column and if the rows in that column is NaN replace it by 0 or values are there in that column replace it as 1

    this below line will change your column to 0

    df.YourColumnName.fillna(0,inplace=True)
    

    Now Rest of the Not Nan Part will be Replace by 1 by below code

    df["YourColumnName"]=df["YourColumnName"].apply(lambda x: 1 if x!=0 else 0)
    

    Same Can Be applied to the total dataframe by not defining the column Name

提交回复
热议问题