Search code examples
pythonpandasfillna

How can i use .fillna with specific values?


df["load_weight"] = df.loc[(df["dropoff_site"] == "HORNSBY BEND") & (df['load_type'] == "BRUSH")].fillna(1000, inplace=True)

i want to change the NaN value in "load_weight" column, but only for the rows that contain "HORNSBY BEND" and "BRUSH", but above code gave me "none" to the whole "load_weight" column, what did i do wrong?


Solution

  • I would use a mask for boolean indexing:

    m = (df["dropoff_site"] == "HORNSBY BEND") & (df['load_type'] == "BRUSH")
    df.loc[m, "load_weight"] = df.loc[m, 'load_weight'].fillna(1000)
    

    NB. you can't keep inplace=True when you assign the output. This is what was causing your data to be replaced with None as methods called with inplace=True return nothing.

    Alternative with only boolean indexing:

    m1 = (df["dropoff_site"] == "HORNSBY BEND") & (df['load_type'] == "BRUSH")
    m2 = df['load_weight'].isna()
    df.loc[m1&m2, "load_weight"] = 1000