Exchange NaN Values in Column of pandas DataFrame by 0 in Python (2 Examples)

In this Python tutorial you’ll learn how to substitute NaN values in a pandas DataFrame by the value 0.

Example Data

import pandas as pd                     # Import pandas
my_df = pd.DataFrame({'A':[1, float('NaN'), 5, 3, float('NaN'), 7, float('NaN')],  # Construct example DataFrame
                      'B':[float('NaN'), 0, float('NaN'), 6, 2, 1, 7]})
print(my_df)                                               # Display example DataFrame in console
#      A    B
# 0  1.0  NaN
# 1  NaN  0.0
# 2  5.0  NaN
# 3  3.0  6.0
# 4  NaN  2.0
# 5  7.0  1.0
# 6  NaN  7.0

Example 1: Replace NaN with 0 in One pandas DataFrame Column

my_df_a = my_df.copy()                     # Duplication of example DataFrame
my_df_a['A'] = my_df_a['A'].fillna(0)             # Exchanging NaN in single variable
print(my_df_a)                                    # Showing DataFrame with 0 in single variable
#      A    B
# 0  1.0  NaN
# 1  0.0  0.0
# 2  5.0  NaN
# 3  3.0  6.0
# 4  0.0  2.0
# 5  7.0  1.0
# 6  0.0  7.0

Example 2: Replace NaN with 0 in Every Column of pandas DataFrame

my_df_b = my_df_a.fillna(0)                 # Exchanging NaN in each variable
print(my_df_b)                                    # Showing DataFrame with 0 in each variable
#      A    B
# 0  1.0  0.0
# 1  0.0  0.0
# 2  5.0  0.0
# 3  3.0  6.0
# 4  0.0  2.0
# 5  7.0  1.0
# 6  0.0  7.0

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top