pandas :使用日期列表和DateTimeIndex访问数据 [英] Pandas: Accessing data with list of dates and DateTimeIndex

查看:107
本文介绍了 pandas :使用日期列表和DateTimeIndex访问数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 DateTimeIndex 的熊猫数据框:

I have a pandas DataFrame with a DateTimeIndex:

                           A          B
2016-04-25 18:50:06   440.967796   201.049600  
2016-04-25 18:50:13   441.054995   200.767034  
2016-04-25 18:50:20   441.142337   200.484475
...
2016-07-27 18:50:06   440.967796   201.049600  
2016-07-27 18:50:13   441.054995   200.767034  
2016-07-27 18:50:20   441.142337   200.484475

我想提取给定日期的所有数据 yyyy-mm-dd 使用日期列表: ['2016-04-25','2016-04-28',...]

I would like to extract all the data of a given date yyyy-mm-dd using a list of dates: ['2016-04-25','2016-04-28',...]

我尝试了以下操作:

 df[df.index.isin(['2016-04-25', '2016-04-26'])]

 Empty DataFrame

我要检索此列表中给出的日期的所有数据(全天数据)

I would like to retrieve all the data (data of the whole day) of the dates given in this list

推荐答案

您需要先通过此解决方案

df = df[df.index.normalize().isin(['2016-04-25', '2016-04-26'])]







df = df[df.index.floor('D').isin(['2016-04-25', '2016-04-26'])]

另一个解决方案是比较 DatetimeIndex.date ,但必须使用 numpy.in1d 代替 isin

Another solution is compare DatetimeIndex.date, but necessary use numpy.in1d instead isin:

df = df[np.in1d(df.index.date, pd.to_datetime(['2016-04-25', '2016-04-26']).date)]

或比较创建的字符串 DatetimeIndex.strftime

Or compare strings created DatetimeIndex.strftime:

df = df[np.in1d(df.index.strftime('%Y-%m-%d'), ['2016-04-25', '2016-04-26'])]







print (df)
                              A           B
2016-04-25 18:50:06  440.967796  201.049600
2016-04-25 18:50:13  441.054995  200.767034
2016-04-25 18:50:20  441.142337  200.484475

这篇关于 pandas :使用日期列表和DateTimeIndex访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆