Python-选择特定时间范围的pandas

标签 python pandas time financial

这里是Python新手,但我有一些数据是日内财务数据,可以追溯到2012年,所以每天都有相同的时间(每天相同的交易时段),但只是不同的日期。我希望能够从数据中选择某些时间并检查该时间段相应的 OHLC 数据,然后对其进行一些分析。

所以目前它是一个 CSV 文件,我正在做:

import pandas as pd
data = pd.DataFrame.read_csv('data.csv')

date = data['date']
op = data['open']
high = data['high']
low = data['low']
close = data['close']
volume = data['volume']

问题是日期列的格式为“dd/mm/yyyy 00:00:00”作为一个字符串或其他任何内容,因此是否仍然可以在某个时间之间进行选择,例如“09: 00:00”和“10:00:00”?或者我是否必须将该时间位与日期分开并使其成为自己的列?如果是这样,怎么办?

所以我相信pandas有一个 Between_time() 函数,但这似乎需要一个DataFrame,那么我如何将它转换为DataFrame,那么我应该能够使用 Between_time 函数在我想要的时间之间选择。另外,因为显然有数千天,所有这些天都有自己的“xx:xx:xx”到“xx:xx:xx”,我想拉出我想要每天查看的同一时间段,而不仅仅是第一批“xx:xx:xx”到“xx:xx:xx”,因为它沿着数据向下移动,如果这有意义的话。谢谢!!

最佳答案

考虑数据帧df

from pandas_datareader import data

df = data.get_data_yahoo('AAPL', start='2016-08-01', end='2016-08-03')
df = df.asfreq('H').ffill()
<小时/>

选项 1
index 转换为系列,然后 dt.hour.isin

slc = df.index.to_series().dt.hour.isin([9, 10])
df.loc[slc]

选项 2
numpy 广播

slc = (df.index.hour[:, None] == [9, 10]).any(1)
df.loc[slc]

enter image description here

<小时/>

对评论的回复

要获得每天该时间段内的范围,请使用 resample + agg + np.ptp(峰值到峰值)

df.loc[slc].resample('D').agg(np.ptp)

关于Python-选择特定时间范围的pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41711576/

相关文章:

PHP:使用 DateTime 类转换日期

java - android 在不同时间计算的相等日期的毫秒数确实不同

java - 针对使用 LocalDateTime 的 api 进行测试

python - 预建索引的数据清理后果

python - Pandas DataFrame : Unusual Behaviour with json. 转储(额外的双引号)

python-3.x - 连接到 "Iex"或 "morningstar"并检索数据

python和数据帧: group by week and calculate the sum and difference

python - 为什么我的 python 脚本(导入 docker-py 包(下面链接))给出错误而不是运行我的 docker 容器?

python - 无法在python列表中进行编码和解码

python - 从 txt 文件读取到 3 个不同列表时如何防止硬编码 - python