So I am trying to use Pandas to replace all NaN values in a table with the median across a particular range. I am working with a larger dataset but for example
np.random.seed(0)
rng = pd.date_range('2020-09-24', periods=20, freq='0.2H')
df = pd.DataFrame({ 'Date': rng, 'Val': np.random.randn(len(rng)), 'Dist' :np.random.randn(len(rng)) })
df.Dist[df.Dist<=-0.6] = np.nan
df.Val[df.Val<=-0.5] = np.nan
What I want to do is replace the NaN values for Val and Dist with the median value for each hour for that column. I have managed to get the median values in a separate reference table:
df.set_index('Date', inplace=True)
df = df.assign(Hour = lambda x : x.index.hour)
df_val = df[["Val", "Hour"]].groupby("Hour").median()
df_dist = df[["Dist", "Hour"]].groupby("Hour").median()
But now I have tried all of the below commands in various forms and cannot work out how to fill NaN values.
df[["Val","Hour"]].mask(df['Val'].isna(), df_val.iloc[df.Hour], inplace=True)
df.where(df['Val'].notna(), other=df_val[df.Hour],axis = 0)
df["Val"] = np.where(df['Val'].notna(), df['Val'], df_val(df.Hour))
df.replace({"Val":{np.nan:df_val[df.Hour]}, "Dist":{np.nan:df_dist[df.Hour]}})

