【问题标题】:Pandas Dataframe time series resample, how to modify bins to fit underlying dataset start and end timePandas Dataframe 时间序列重新采样,如何修改 bin 以适应底层数据集的开始和结束时间
【发布时间】:2021-11-15 21:23:36
【问题描述】:

我对一些股市数据进行了练习,数据框从 09:30 开始,到 16:00 结束。我想重新采样到 4 小时间隔使用

agg_dict = {'open': 'first','high': 'max','low': 'min','cls': 'last','vol': 'sum'}
data_4hour = fullRth.resample('4H',label='left',origin='end').agg(agg_dict).dropna().round(2).sort_index(ascending=False)

我的输出是:

data_4hour.head()

                          open    high    low      cls       vol
time                    
2021-09-03 11:59:00     452.59  453.63  452.48  453.06  21407679
2021-09-03 07:59:00     451.98  453.05  451.55  452.59  16481655
2021-09-02 11:59:00     453.47  453.52  451.91  453.20  22855174
2021-09-02 07:59:00     453.32  454.05  453.05  453.48  14509768
2021-09-01 11:59:00     452.37  453.11  451.54  451.82  24303603

我想要的输出应该是这样的:

                          open    high    low      cls       vol
time                    
2021-09-03 11:59:00     452.59  453.63  452.48  453.06  21407679
2021-09-03 09:30:00     451.98  453.05  451.55  452.59  16481655
2021-09-02 11:59:00     453.47  453.52  451.91  453.20  22855174
2021-09-02 09:30:00     453.32  454.05  453.05  453.48  14509768
2021-09-01 11:59:00     452.37  453.11  451.54  451.82  24303603

据我了解,分箱取决于日期时间(?)。 我已经在github 上阅读了这个答案,但是从 2013 年开始,我想知道是否有可能这样做。

我正在使用: 蟒蛇:3.9.6.final.0 熊猫:1.3.0 numpy : 1.21.1

【问题讨论】:

    标签: python python-3.x pandas pandas-resample


    【解决方案1】:

    我做了一些工作。如果有人有更好的解决方案,我想阅读它。 首先,我确保垃圾箱中的值正确定位。 然后我对上面的 DataFrame 做了:

    # separating date and time from DatetimeIndex into new columns
    data_4hour['times'] = data_4hour.index.time.astype(str)
    data_4hour['date'] = data_4hour.index.date.astype(str)
    
    # changing the values with `np.where` 
    data_4hour['times'] = np.where(data_4hour['times']=='07:59:00','09:30:00',data_4hour['times'])
    
    # concatenate date and time column into Datetime column
    data_4hour['datetime'] = pd.to_datetime(data_4hour['date'] + ' ' + data_4hour['times'])
    
    data_4hour.reset_index(inplace=True)
    
    del data_4hour['time'],data_4hour['times'],data_4hour['date']
    
    data_4hour = data_4hour.set_index('datetime')
    
    print(data_4hour)
    
                           open    high     low     cls       vol
    datetime                                                     
    2021-09-03 11:59:00  452.59  453.63  452.48  453.06  21407679
    2021-09-03 09:30:00  451.98  453.05  451.55  452.59  16481655
    2021-09-02 11:59:00  453.47  453.52  451.91  453.20  22855174
    2021-09-02 09:30:00  453.32  454.05  453.05  453.48  14509768
    2021-09-01 11:59:00  452.37  453.11  451.54  451.82  24303603
    
    

    【讨论】:

      猜你喜欢
      • 2018-02-05
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      相关资源
      最近更新 更多