使用前几天同一小时的平均值填充NaN

问题描述 投票:5回答:1

我想用前几天相同小时 - 分钟的平均值来填充NaN。为了简化,这是我的df的一个例子。

timstamp         data
22/04/2016 09:00 1
22/04/2016 09:05 2
...
23/04/2016 09:00 3
23/04/2016 09:05 4
...
24/04/2016 09:00 5
24/04/2016 09:05 6
...
25/04/2016 09:00 7
25/04/2016 09:05 8
...
25/04/2016 10:00 NaN
25/04/2016 10:05 NaN

真实数据包含连续5分钟间隔的许多天。

df = df.groupby(df.index.minute).fillna(df.data.rolling(3).mean())试图在过去的几天里从前一小时开始做滚动平均值,但它没有奏效。

df = df.groupby(df.index.minute).ffill()的另一种方法取前两行(即7和8)的值,该值来自同一天前一小时的相同分钟。

但是,我想要以下结果:

timstamp         data
22/04/2016 09:00 1
22/04/2016 09:05 2
...
23/04/2016 09:00 3
23/04/2016 09:05 4
...
24/04/2016 09:00 5
24/04/2016 09:05 6
...
25/04/2016 09:00 7
25/04/2016 09:05 8
25/04/2016 10:00 3
25/04/2016 10:05 4

其中值3(倒数第二行)是前几天相同小时 - 分钟(平均值为1,3和5)的值的平均值,而4(最后一行)是平均值2,4, 6.鉴于我的df的大小,我想从前几天采取一个平均值。

编辑 我越走越近了。使用以下代码,数据的平均值按照我想要的小时和分钟计算:

df.set_index('timstamp', inplace=True)
df=df.groupby([df.index.hour, df.index.minute]).mean()
df.index.names = ["hour", "minute"]

但是,它使用整个数据来获得小时分钟的平均值。我想要的是仅使用与前几天相同的小时 - 分钟,我可以在其中设置计算中的过去天数。然后,得到的平均值应用于填充NaN。

python pandas group-by time-series fill
1个回答
1
投票

我们试试这个:

# time sample every 5 mins
idx = pd.date_range('2018-01-01', '2018-01-31', freq='300s')
np.random.seed(2019)

# create toy data
df = pd.DataFrame({'idx':idx,
                   'data':np.random.uniform(0,5, len(idx))})
df.loc[np.random.uniform(0,1,len(idx)) > 0.95, 'data'] = None

# means by the hour, can also use median
means = df.resample('H', on='idx').data.mean()

# get the timestamp on the hour
df['hour'] = df['idx'] - pd.to_timedelta(df.idx.dt.minute, unit='m')

# get the hour stamp of previous day
df['hour'] -= pd.to_timedelta(1, unit='d')

# update NaN
# df.loc[df.data.isna(), 'data'] = means[nan_hour]

# the original mapping raised a ValueError due to duplicates in nan_hour
df.loc[df.data.isna(), 'data'] = df.loc[df.data.isna(), 'hour'].\   
                                    replace({'hour': means})
© www.soinside.com 2019 - 2024. All rights reserved.