-2

By doing df.groupby('acc_count', as_index=False)['avg_spd'].median()

I got

acc_count          avg_spd
        0           20.94
        1           24.42
        2           26.035
        3           33.27
        4           33.46
        5           36.07
        6           35.03
        7           33.49
        8           71.85

In my dataframe, I have null values in the avg_spd column. I want that to be imputed with the above values of avg_spd based on acc_count. for e.g., rows where acc_count=0 and avg_spd is null I need to replace null with 20.940

How can I do that in pandas?

1 Answers1

0

You can create a dictionary of acc_count as keys and the value should be the integer to be placed if avg_spd is null.

For example,

dict = {0 : 20.940, 1 : 20.00 ,...}

Then the following logic can be utilized,

df_new = df.groupby('acc_count', as_index=False)['avg_spd'].median()
df_new['avg_spd'].fillna(dict[df_new['acc_count']], inplace=True)
Nauman Naeem
  • 408
  • 3
  • 12