Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Replace NaN Value by Zero in Python

Replacing NaN with Zero in a Dataset

Condition for Replacing NaN with Zero in a Dataset

  • Description:
    In data preprocessing, missing values represented by NaN (Not a Number) can be problematic for analyses and machine learning models. Replacing NaN values with zero is a common approach to handle missing data. The Pandas library provides the fillna() method to replace NaN values efficiently.
Step-by-Step Process
  • Import Libraries:
    Import the necessary libraries, such as Pandas, for data manipulation.
  • Load the Dataset:
    Load your dataset into a Pandas DataFrame.
  • Identify Missing Values:
    Use isna() or isnull() to check for NaN values.
  • Replace NaN with Zero:
    Use the fillna(0) method to replace all NaN values in the dataset with zero.
  • Save or Use the Updated DataFrame:
    Save the modified dataset or proceed with further analysis.
Sample Source Code
  • # Code for Filling NaN Values by Zeros

    import pandas as pd

    data = {
    'Product': ['A', 'B', 'C', 'D', 'E'],
    'Price': [10.5, 20.5, None, 40.0, 15.0],
    'Units Sold': [100, None, 200, 150, 50],
    'Discount': [None, 5.0, None, 10.0, None]
    }

    df = pd.DataFrame(data)

    print("Original DataFrame:")
    print(df)

    # Replace NaN values with 0
    df_filled = df.fillna(0)

    print("\nDataFrame after Replacing NaN with 0:")
    print(df_filled)
Screenshots
  • Replacing NaN with Zero Output