Python:使用 Pandas 从数据框中选择特定日期

标签 python pandas dataframe time-series

以下简短脚本使用 findatapyDukascopy 收集数据网站。请注意,此包使用 Pandas,不需要单独导入。

from findatapy.market import Market, MarketDataRequest, MarketDataGenerator

market = Market(market_data_generator=MarketDataGenerator())
md_request = MarketDataRequest(start_date='08 Feb 2017', finish_date='09 Feb 2017', category='fx', fields=['bid', 'ask'], freq='tick', data_source='dukascopy', tickers=['EURUSD'])

df = market.fetch_market(md_request)

#Group everything by an hourly frequency.
df=df.groupby(pd.TimeGrouper('1H')).head(1)

#Deleting the milliseconds from the Dateframe
df.index =df.index.map(lambda t: t.strftime('%Y-%m-%d %H:%M:%S'))

#Computing Average between columns 1 and 2, and storing it in a new one.
df['Avg'] = (df['EURUSD.bid'] + df['EURUSD.ask'])/2

结果是这样的:

enter image description here

到目前为止,一切都正常运行,但我需要从该数据框中提取特定的时间。比方说,我想在特定时间上午 10:00:00 选择所有值(出价、要价、平均...或其中之一)。

通过查看其他posts ,我想我可以做这样的事情:

match_timestamp = "10:00:00"
df.loc[(df.index.strftime("%H:%M:%S") == match_timestamp)]

但结果是一条错误消息:

AttributeError: 'Index' object has no attribute 'strftime'

我什至无法执行 df.index.hour,它曾经在我删除毫秒的行之前工作(dtype 是 datetime64[ns] 直到那一点),之后 dtype 是一个“对象”。看来我需要反转此格式才能使用 strftime。

你能帮帮我吗?

最佳答案

你应该看看resample :

df = df.resample('H').first()  # resample for each hour and use first value of hour

然后:

df.loc[df.index.hour == 10]  # index is still a date object, play with it

如果你不喜欢那样,你可以像这样将你的索引设置为一个日期时间对象:

df.index = pd.to_datetime(df.index)

那么你的代码应该可以正常工作了

关于Python:使用 Pandas 从数据框中选择特定日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46674889/

相关文章:

python-3.x - 有没有更好的方法来获取标签作为数据框中没有单个缺失值的那些特征(列)的列表?

python-3.x - 在 matplotlib 子图中添加一行

python - 如何在Python的条件下增加数据帧列?

python - 如何在直方图上设置轴并交换 x 轴和 y 轴?

python - 测量视频中两个轮廓之间的距离? OpenCV Python

python - pandas:使用 ~ 删除数据帧的子集

Python Pandas 数据框行条目无法按条件进行比较

r - 如何在 r 中系统地重新排序列?

Python - 数据框列在 '.' 之后用大写字母重命名

python - 为列中的所有值 reshape 数据框