Replace NaN values with Zero in Specific Column(s)

To replace NaN values with Zero in Specific Column of DataFrame, first access the column(s) using indexing, and then call fillna() method. Pass 0 as argument to fillna() method.

In this tutorial, we will learn how to replace NaN values with 0 in specified columns using DataFrame.fillna() method.

Examples

Replace NaN with 0 in only One Column of DataFrame

In the following program, we fill NaN values of col_0 only.

Example.py

</>
Copy
import pandas as pd
import numpy as np

data = {'col_0': [11, np.nan, np.nan, np.nan], 'col_1': [np.nan, 55, 77, 66]}
df = pd.DataFrame(data)

df['col_0'] = df['col_0'].fillna(0)
print(df)

Output

   col_0  col_1
0   11.0    NaN
1    0.0   55.0
2    0.0   77.0
3    0.0   66.0

Replace NaN with 0 in Two Columns of DataFrame

In the following program, we fill NaN values of col_0 and col_1.

Example.py

</>
Copy
import pandas as pd
import numpy as np

data = {'col_0': [11, np.nan, np.nan, np.nan], 'col_1': [np.nan, 55, 77, 66], 'col_2': [np.nan, 99, np.nan, 88]}
df = pd.DataFrame(data)

cols = ['col_0', 'col_1']

df[cols] = df[cols].fillna(0)
print(df)

Output

   col_0  col_1  col_2
0   11.0    0.0    NaN
1    0.0   55.0   99.0
2    0.0   77.0    NaN
3    0.0   66.0   88.0

Conclusion

In this Pandas Tutorial, we learned how to replace NaN values in select column(s) with 0 using DataFrame.fillna() method.