在 Python 中按指定时间间隔分组和重新采样

问题描述

我如何使用前向填充 df 和后向填充 1minffill 频率对下面的 bfill 重新采样(使用 id }) 时间间隔groupby('id')2017-01-01 00:00:00,即第一个时间戳是2017-01-05 00:00:00,最后一个时间戳是2017-01-01 00:00:00

2017-01-05 00:00:00

我试过了:

          id   timestamp                data  

      1    1   2017-01-02 13:14:53.040  10.0
      2    1   2017-01-02 16:04:43.240  11.0  
                           ...
      4    2   2017-01-02 15:22:06.540   1.0  
      5    2   2017-01-03 13:55:34.240   2.0  
                           ...

但这并没有指定所需的时间间隔 pd.DataFrame(df.set_index('timestamp').groupby('id',sort=True)['data'].resample('1min').ffill().bfill()) -2017-01-01 00:00:00

然后我尝试了:

2017-01-05 00:00:00

并发现错误:


r = pd.to_datetime(pd.date_range(start='2017-01-01 00:00:00',end='2017-01-05 00:00:00',freq='1min'))

pd.DataFrame(df.reset_index().set_index('timestamp').groupby('id',sort=True).reindex(r)['data'].resample('1min').ffill().bfill())

更新:

对于示例数据 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-202-344bb3281e2e> in <module> 5 r = pd.to_datetime(pd.date_range(start='2017-01-01 00:00:00',freq='1min')) 6 ----> 7 pd.DataFrame(df.reset_index().set_index('timestamp').groupby('id',sort=True).reindex(r)['data'].resample('1min').ffill().bfill()) 8 ~\AppData\Roaming\Python\Python38\site-packages\pandas\core\groupby\groupby.py in __getattr__(self,attr) 701 return self[attr] 702 --> 703 raise AttributeError( 704 f"'{type(self).__name__}' object has no attribute '{attr}'" 705 ) AttributeError: 'DataFrameGroupBy' object has no attribute 'reindex'

df_sub_data

我试过了:

{'timestamp': {781681: Timestamp('2021-03-11 17:17:19.920000'),1036818: Timestamp('2021-03-11 17:59:56.040000'),677981: Timestamp('2021-03-11 19:25:59.090000')},'data': {781681: 25.0,1036818: 24.0,677981: 23.0},'id': {781681: 100,1036818: 100,677981: 100}}

它返回了一个形状为 start = datetime.datetime.now() - pd.to_timedelta("7day") end = datetime.datetime.now() def f(x): r = pd.date_range(start=start,end=end,freq='1min') return x.reindex(r,method='ffill').bfill() df_sub = (df_sub_data.reset_index() .set_index('timestamp') .groupby(['index','id'],sort=False)['data'] .apply(f) .reset_index(level=0,drop=True) .rename_axis(['id','timestamp']) .reset_index() )

的数据框

我想知道,我不应该期望形状是 (30243,3),它是由 (10080,3) 7 天的分钟数给出的吗?样本数据由一个7 x 24 x 60的数据组成。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)