Kab*_*omi 5 python dataframe pandas pandas-groupby
以下数据以5分钟为间隔
数据框名称为 df:
| 脚本 ID | 约会时间 | 打开 | 高的 | 低的 | 关闭 | 体积 | |
|---|---|---|---|---|---|---|---|
| 0 | 201 | 2019-02-04 14:55:00 | 1408.05 | 1408.05 | 1407 | 1408 | 2384 |
| 1 | 201 | 2019-02-04 15:00:00 | 1408 | 1410.6 | 1407.2 | 1408.85 | 12621 |
| 2 | 201 | 2019-02-04 15:05:00 | 1408.85 | 1410.45 | 1407.05 | 1407.05 | 3880 |
| 3 | 201 | 2019-02-04 15:10:00 | 1407.05 | 1409.4 | 1404.85 | 1404.85 | 12992 |
| 4 | 201 | 2019-02-04 15:15:00 | 1404.85 | 1408.7 | 1403.5 | 1404.25 | 30803 |
| 5 | 201 | 2019-02-04 15:20:00 | 1404.25 | 1405 | 1402.7 | 1404.8 | 14624 |
| 6 | 201 | 2019-02-04 15:25:00 | 1404.8 | 1405 | 1402.05 | 1403.8 | 8407 |
| 7 | 201 | 2019-02-05 09:15:00 | 1400 | 1416.05 | 1400 | 1410.75 | 17473 |
尝试通过执行以下代码在 10 分钟内对其进行分组:
df_f = df.groupby(['script_id', pd.Grouper(key='date_time', freq='10T', origin='start')])\
.agg(open=pd.NamedAgg(column='open', aggfunc='first'),
high=pd.NamedAgg(column='high', aggfunc='max'),
low=pd.NamedAgg(column='low', aggfunc='min'),
close=pd.NamedAgg(column='close', aggfunc='last'),
volume=pd.NamedAgg(column='volume', aggfunc='sum'))\
.reset_index()
print(df_f)
Run Code Online (Sandbox Code Playgroud)
结果:
预期结果:- 0,1,2 如下预期应为 3,不应有 4。
| 脚本 ID | 约会时间 | 打开 | 高的 | 低的 | 关闭 | 体积 | |
|---|---|---|---|---|---|---|---|
| 3 | 201 | 2019-02-04 15:25:00 | 1404.8(值为 6) | 1416.05(6 和 7 中最高) | 400(6 和 7 中最低) | 1410.75(值为 7) | 25880(6 和 7 之和) |
我们如何将最后两个 5 分钟的 tf 组合到一个 10 分钟的 tf?
注意:- 两天之间也可能有假期间隔
或许:
a = {'script_id': 'first', 'date_time': 'first', 'open': 'first', 'high':'max', 'low':'min', 'close':'last', 'volume':'sum'}
print(df.groupby(df.index // 2).agg(a))
script_id date_time open high low close volume
0 201 2019-02-04 14:55:00 1408.05 1410.60 1407.00 1408.85 15005
1 201 2019-02-04 15:05:00 1408.85 1410.45 1404.85 1404.85 16872
2 201 2019-02-04 15:15:00 1404.85 1408.70 1402.70 1404.80 45427
3 201 2019-02-04 15:25:00 1404.80 1416.05 1400.00 1410.75 25880
Run Code Online (Sandbox Code Playgroud)