Skip to main content
 首页 » 编程设计

python之Pandas :使用外部系列重新采样

2024年10月25日10lvdongjie

我想使用带有日期时间 在里面。

我的名为 df 的 DataFrame 示例看起来像这样:

(编辑:更正了示例数据集中的一个错误)

Datetime               Volume    Price  
2013-04-15 21:45:00     100      50.00 
2013-04-15 21:47:00     25       50.03 
2013-04-15 21:52:00     15       50.05 
2013-04-15 22:03:00     4        50.07 
2013-04-15 22:04:00     145      50.38 
2013-04-15 22:07:00     68       50.04 
2013-04-15 22:12:00     157      49.93 
2013-04-15 22:13:00     27       50.02 
2013-04-15 22:19:00     37       49.91 

Series 称为 beginpoints(它是每个区间的起点),看起来像:

0      2013-04-15 21:45:00 
1      2013-04-15 22:04:00 
2      2013-04-15 22:13:00 

鉴于我对区间的成交量和开盘价的总和感兴趣,我最终希望得到以下解决方案:

Datetime                Volume     Price  
2013-04-15 21:45:00     144        50.00 
2013-04-15 22:04:00     370        50.38 
2013-04-15 22:13:00     64         50.02 

我知道标准重采样类似于 df.resample('5min', how={'Volume':sum, 'Price':first}) 例如间隔 5 分钟。但是,当我尝试将其修改为我的特定场景并因此使用 df.resample(beginpoints, how={'Volume':sum, 'Price':first}) 我得到一个 值错误。这看起来很简单,但我似乎无法弄清楚我做错了什么。有人知道如何解决这个问题吗?谢谢!

请您参考如下方法:

我会提供一个方法。首先,我重置了beginpoints系列的索引,将beginpoints作为索引。

然后 index 列被提取为一系列以映射 df 中的 Datetime 列。有 Datetime 值不是 beginpoints 的一部分,因此相应的 point N/A。但是由于 Datetime 是排序的,我们可以使用 ffill 来填充这些 N/A。

s = pd.Series(["2013-04-15 21:45:00", "2013-04-15 22:04:00","2013-04-15 22:13:00"], name="beginpoints") 
 
t = s.reset_index().set_index("beginpoints") 
ts = t['index'] 
 
df['point'] = df['Datetime'].map(ts).fillna(method="ffill") 

结果:

              Datetime  Volume  Price  point 
0  2013-04-15 21:45:00     100  50.00      0 
1  2013-04-15 21:47:00      25  50.03      0 
2  2013-04-15 21:52:00      15  50.05      0 
3  2013-04-15 22:03:00       4  50.07      0 
4  2013-04-15 22:04:00     145  50.38      1 
5  2013-04-15 22:07:00      68  50.04      1 
6  2013-04-15 22:12:00     157  49.93      1 
7  2013-04-15 22:13:00      27  50.02      2 
8  2013-04-15 22:19:00      37  49.91      2 

最后,使用groupby根据点计算汇总:

group= df.groupby(['point']) 
 
df2 = pd.DataFrame() 
df2['Datetime'] = group[['Datetime']].first() 
df2['Volume'] = group[['Volume']].sum()  
df2['Price'] = group[['Price']].first() 

结果:

              Datetime  Volume  Price 
0  2013-04-15 21:45:00     144  50.00 
1  2013-04-15 22:04:00     370  50.38 
2  2013-04-15 22:13:00      64  50.02