我有一个缺少值的数据集和一个Datetimeindex。我想用在同一个月、一天和同一小时报告的其他值的平均值来填充这个值。如果在这个特定的月份/日/小时没有报告所有年份的值,我希望得到所报告的最近小时的内插平均值。我怎样才能做到这一点?现在我的方法是:
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
发布于 2022-05-13 00:35:57
将GroupBy.transform
与mean
一起用于每个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://stackoverflow.com/questions/72226579
复制