Skip to content
TheChatArchiveThe Chat Archive
Unspecified model (huggingface.xxx)Hugging Face ShareLM (browser-extension contributions)

In pandas replace NaN by 0 across all df

  1. User

    In pandas replace NaN by 0 across all df

  2. Assistant

    You can use the fillna() function in pandas to replace NaN values with 0 across an entire DataFrame. Here is an example: import pandas as pd import numpy as np

    create a sample dataframe with NaN values

    df = pd.DataFrame({ 'A': [1, 2, np.nan, 4], 'B': [np.nan, 5, 6, 7], 'C': [8, np.nan, 10, 11] })

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

    replace NaN with 0 across all columns

    df = df.fillna(0)

    print("\nDataFrame after replacing NaN with 0:") print(df) Copied This will output: Original DataFrame: A B C 0 1.0 NaN 8.0 1 2.0 5.0 NaN 2 NaN 6.0 10.0 3 4.0 7.0 11.0

    DataFrame after replacing NaN with 0: A B C 0 1.0 0.0 8.0 1 2.0 5.0 0.0 2 0.0 6.0 10.0 3 4.0 7.0 11.0 Copied Note that fillna() returns a new DataFrame with the replaced values, it does not modify the original DataFrame in place. If you want to modify the original DataFrame, use the inplace=True parameter: df.fillna(0, inplace=True) Copied

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.