k.k*_*o3n 5 python group-by time-series fill pandas
我想使用前几天相同小时数中的平均值来填充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
Run Code Online (Sandbox Code Playgroud)
实际数据包含连续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
Run Code Online (Sandbox Code Playgroud)
其中值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"]
Run Code Online (Sandbox Code Playgroud)
但是,它使用整个数据来获取小时-分钟平均值。我想要的是只使用与前几天相同的小时-分钟,在这里我可以设置计算中的过去几天。然后,所得平均值将用于填充NaN。
让我们试试这个:
# 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})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |