如何在 Python 中将 1 分钟开盘-最高-最低-收盘数据转换为另一个时间范围(fx:5 分钟、1 小时)?

Vin*_*rue 6 python finance currency dataframe pandas

我对 Python 和 StackOverflow 还很陌生,所以如果我在这篇文章中犯了错误,请多多包涵。

我有一个 Pandas 数据框,其中包含一种货币的 1 分钟开盘价、最高价、最低价和收盘价数据,以时间为索引。我该如何将其转换为一个数据帧,例如包含 5 分钟开盘价、最高价、最低价、收盘价数据,并使时间戳也适合?以下是打印出的 1 分钟数据的示例:

                   ZARJPY_open  ZARJPY_high  ZARJPY_low  ZARJPY_close
time                                                            
201901011700        7.589        7.589       7.589         7.589
201901011701        7.590        7.590       7.590         7.590
201901011702        7.589        7.590       7.589         7.589
201901011703        7.590        7.593       7.590         7.593
201901011705        7.592        7.593       7.592         7.593
Run Code Online (Sandbox Code Playgroud)

我想把它变成:

                  ZARJPY_open  ZARJPY_high  ZARJPY_low  ZARJPY_close
time                                                            
201901011700        7.589        7.593       7.589         7.593
201901011706                  -next 5 minutes-                     
Run Code Online (Sandbox Code Playgroud)

如有任何帮助,我们将不胜感激:)

编辑:时间戳采用 YYYYMMDDHHmm(年、月、日、小时、分钟)格式

Roy*_*012 18

您可以使用 5 分钟石斑鱼对象:

# parse the time. 
df.time = pd.to_datetime(df.time, format="%Y%m%d%H%M")

#make the time the index. 
df = df.set_index("time")

# group in 5-minute chunks. 
t = df.groupby(pd.Grouper(freq='5Min')).agg({"ZARJPY_open": "first", 
                                             "ZARJPY_close": "last", 
                                             "ZARJPY_low": "min", 
                                             "ZARJPY_high": "max"})
t.columns = ["open", "close", "low", "high"]
print(t)
Run Code Online (Sandbox Code Playgroud)

结果是:

                      open  close    low   high
time                                           
2019-01-01 17:00:00  7.589  7.593  7.589  7.593
2019-01-01 17:05:00  7.592  7.593  7.592  7.593
Run Code Online (Sandbox Code Playgroud)