Categories
Python Answers

How to replace NaN values by zeroes in a column of a Python Pandas Dataframe?

Spread the love

Sometimes, we want to replace NaN values by zeroes in a column of a Python Pandas Dataframe.

In this article, we’ll look at how to replace NaN values by zeroes in a column of a Python Pandas Dataframe.

How to replace NaN values by zeroes in a column of a Python Pandas Dataframe?

To replace NaN values by zeroes in a column of a Python Pandas Dataframe, we can use the DataFrame’s fillna method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'col': [1, 2, 3, None, None]}).fillna(0)
print(df)

We create a DataFrame with pd.DataFrame({'col': [1, 2, 3, None, None]}).

None are the NaN values in the DataFrame.

Then we call fillna to replace None with 0 and assign the DataFrame to df.

Therefore, df is:

   col
0  1.0
1  2.0
2  3.0
3  0.0
4  0.0

Conclusion

To replace NaN values by zeroes in a column of a Python Pandas Dataframe, we can use the DataFrame’s fillna method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *