我有一個缺少值和日期時間索引的資料集。我想用在同一月、同一天和同一小時報告的其他值的平均值填充這個值。如果所有年份在這個特定的月/日/小時都沒有報告值,我想獲得報告的最近小時的插值平均值。我怎樣才能做到這一點?現在我的方法是這樣的:
df_Na = df_Na[df_Na['Generation'].isna()]
df_raw = df_raw[~df_raw['Generation'].isna()]
# reduce to month
same_month = df_raw[df_raw.index.month.isin(df_Na.index.month)]
# reduce to same day
same_day = same_month[same_month.index.day.isin(df_Na.index.day)]
# reduce to hour
same_hour = same_day[same_day.index.hour.isin(df_Na.index.hour)]
df_Na 都是我喜歡填充的缺失值,df_raw 都是我喜歡從中獲取平均值的報告值。我有一個龐大的資料集,這就是為什么我想不惜一切代價避免 for 回圈。
我的資料如下所示:df_Na
Generation
2017-12-02 19:00:00 NaN
2021-01-12 00:00:00 NaN
2021-01-12 01:00:00 NaN
..............................
2021-02-12 20:00:00 NaN
2021-02-12 21:00:00 NaN
2021-02-12 22:00:00 NaN
df_raw
Generation
2015-09-12 00:00:00 0.0
2015-09-12 01:00:00 19.0
2015-09-12 02:00:00 0.0
..............................
2021-12-11 21:00:00 0.0
2021-12-11 22:00:00 180.0
2021-12-11 23:00:00 0.0
uj5u.com熱心網友回復:
使用GroupBy.transformwithmean表示平均值MM-DD HH,并將缺失值替換為DataFrame.fillna:
df = df.fillna(df.groupby(df.index.strftime('%m-%d %H')).transform('mean'))
然后如果需要添加DataFrame.interpolate:
df = df.interpolate(method='nearest')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474733.html
上一篇:標記連續觀察并創建注冊范圍
