How can i use .fillna with specific values?

Question:

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?

Asked By: Huesca Rashad

||

Answers:

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
Answered By: mozway

Instead of fillna, you can directly use df.loc to do the required imputation

df.loc[((df['dropoff_site']=='HORNSBY BEND')&(df['load_type']=='BRUSH')
&(df['load_weight'].isnull())),'load_weight'] = 1000
Answered By: mahak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.