replace nans with 0 in df in python

To replace NaN values with 0 in a pandas dataframe, you can use the fillna() method. Here's an example:

main.py
import pandas as pd

# create a sample dataframe with NaN values
df = pd.DataFrame({'a': [1, 2, None], 'b': [4, None, 6], 'c': [None, None, None]})
print(df)

# replace NaN with 0
df = df.fillna(0)
print(df)
208 chars
10 lines

Output:

main.py
     a    b    c
0  1.0  4.0  NaN
1  2.0  NaN  NaN
2  NaN  6.0  NaN

     a    b    c
0  1.0  4.0  0.0
1  2.0  0.0  0.0
2  0.0  6.0  0.0
137 chars
10 lines

This will replace all NaN values in the dataframe with 0.

related categories

gistlibby LogSnag