[Python] How do I replace "NaN" in a pandas dataframe with a dictionary?

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    Sample dataframe:

    df = pd.DataFrame([[1, {'t': 1}], [2, {'t': 2}], [3, np.nan], [4, np.nan]], columns=['A', 'B'])


    A B
    0 1 {'t': 1}
    1 2 {'t': 2}
    2 3 NaN
    3 4 NaN


    What I want:

    A B
    0 1 {'t': 1}
    1 2 {'t': 2}
    2 3 {'t': 0}
    3 4 {'t': 0}


    For some reason, the below does not work -

    df.fillna({'B': {'t': 0}}, inplace=True)


    Is there a restriction on what values can be used for fillna?

    I have this solution which works,

    df['B'] = df['B'].mask(df['B'].isna(), {'t': 0})


    but I want to know if there is a better way to do this? For example, this fails if 'B' does not exist in the dataframe, whereas the fillna doesn't fail in similar case

    Continue reading...

Compartilhe esta Página