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

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

    There is a method .fillna() on DataFrames which does what you need. For example:

    df = df.fillna(0)  # Replace all NaN values with zero, returning the modified DataFrame
    

    or

    df.fillna(0, inplace=True)   # Replace all NaN values with zero, updating the DataFrame directly
    

提交回复
热议问题