How to change nan values to zero in pandas DataFrame columns?

In this Python Data Analysis tutorial we will learn how to replace empty values with zeros in a complete DataFrame or one or more of of its columns.

Example DataFrame

We’ll import Data Analysis libraries pandas and numpy. Numpy will be used to generate some a few Python lists, some of them containing empty (nan) values.

import pandas as pd
import numpy as np

interviewed = [32, np.nan, 49, 40, np.nan]
hired = [6, pd.NA, 7, 5, 9]
dates = pd.date_range (start='1/29/2023', periods = 5, freq = 'B' )

We will now construct our DataFrame:

hiring = pd.DataFrame (dict (dates = dates, interviewed = interviewed, hired = hired))

And look into its values:

hiring.head()

Here is the data:

datesinterviewedhired
02023-01-3032.06
12023-01-31NaN<NA>
22023-02-0149.07
32023-02-0240.05
42023-02-03NaN9

Replace empty nan values with zero

We will use the following code to change all empty values to zero. Note that we pass a list of possible empty values to the replace method.

hiring = hiring.replace([np.nan, pd.NA,'', None], 0)
hiring.head()

Here’s our DataFrame:

datesinterviewedhired
02023-01-3032.06
12023-01-310.00
22023-02-0149.07
32023-02-0240.05
42023-02-030.09

Change nan to 0 in a specific pandas column

We are able also to selectively modify empty values in one or multiple columns of our DataFrame:

hiring['interviewed'].replace([np.nan, pd.NA,'', None], 0)

This will return the following series:

0    32.0
1     0.0
2    49.0
3    40.0
4     0.0
Name: interviewed, dtype: float64

Modify nans in multiple DataFrame columns

In the same way we can replace empty values in several columns:

hiring[['interviewed','hired']].replace([np.nan, pd.NA,'', None], 0)

Replace empty values by a string

In this case we’ll swap the empty values with the string value None

hiring[['interviewed','hired']].replace([np.nan, pd.NA,'', None], 'None')

Additional learning

How to change column values in Pandas DataFrames?