What is the 25th percentile option when transforming NaN values in a df?

Viewed 95

If I was to do a groupby fillna using median I understand that I would do the following:

df[cols].fillna(df.groupby(['year'])[cols].transform('median'))

However, if I want to fill with the 25th percentile instead, what would replace 'median'?

2 Answers

You can use np.nanpercentile:

df[cols].fillna(df.groupby(["year"])[cols].transform(np.nanpercentile, q=25))

You could also avoid using numpy and use directly panda’s .quantile()

df.groupby('year')[cols].transform(lambda x: x.quantile(.25))
Related