Python Pandas – Replace NaN values with zeros

In this post we will be creating a Python script that will replace any NaN values present with zeros within a Pandas data frame. Pandas is a Python library which is an amazing tool for data analysis and manipulation.

In this example our data will be a CSV file that we’ll be reading from in Python, a sample of the data can be seen in the image below.

To load the CSV data in to a Pandas data frame we would use the snippet of code below.

import pandas as pd

df = pd.read_csv('Sample.csv')
print(df)

The snippet of code above would return the following as output where we can see the NaN values present.

   Rank  NA_Sales  EU_Sales  JP_Sales  Other_Sales  Global_Sales
0     1       NaN     29.02      3.77         8.46         82.74
1     2     29.08      3.58       NaN          NaN         40.24
2     3       NaN       NaN      3.79          NaN         35.82
3     4     15.75       NaN       NaN         2.96         33.00
4     5       NaN      8.89       NaN         1.00           NaN
5     6       NaN       NaN       NaN          NaN         30.26
6     7     11.38       NaN       NaN         2.90         30.01
7     8       NaN      9.20      2.93         2.85           NaN
8     9     14.59      7.06      4.70         2.26         28.62
9    10     26.93       NaN      0.28         0.47         28.31

To replace the NaN values as seen above with zeros instead, we would use the following.

df = df.fillna(0)
print(df)

As a result our data frame would now be seen as.

   Rank  NA_Sales  EU_Sales  JP_Sales  Other_Sales  Global_Sales
0     1      0.00     29.02      3.77         8.46         82.74
1     2     29.08      3.58      0.00         0.00         40.24
2     3      0.00      0.00      3.79         0.00         35.82
3     4     15.75      0.00      0.00         2.96         33.00
4     5      0.00      8.89      0.00         1.00          0.00
5     6      0.00      0.00      0.00         0.00         30.26
6     7     11.38      0.00      0.00         2.90         30.01
7     8      0.00      9.20      2.93         2.85          0.00
8     9     14.59      7.06      4.70         2.26         28.62
9    10     26.93      0.00      0.28         0.47         28.31

Leave a Reply