select dataframe rows (datetimeindex) by a list of datetime.date

做~自己de王妃 提交于 2020-01-15 09:15:49

问题


the df looks like this:

DateTime
2017-07-10 03:00:00    288.0
2017-07-10 04:00:00    306.0
2017-08-10 05:00:00    393.0
2017-08-10 06:00:00    522.0
2017-09-10 07:00:00    487.0
2017-09-10 08:00:00    523.0
2017-10-10 09:00:00    585.0

Question how to select row that in a list of dates:

['2017-07-10', '2017-09-10']

to have:

DateTime
2017-07-10 03:00:00    288.0
2017-07-10 04:00:00    306.0
2017-09-10 07:00:00    487.0
2017-09-10 08:00:00    523.0

Thanks


回答1:


Assuming the Datetime is index, try with the below:

to_search=['2017-07-10', '2017-09-10']
df[df.index.to_series().dt.date.astype(str).isin(to_search)]

                        1
DateTime                  
2017-07-10 03:00:00  288.0
2017-07-10 04:00:00  306.0
2017-09-10 07:00:00  487.0
2017-09-10 08:00:00  523.0



回答2:


Given that the dates in your list contain up to the daily information, you could start by flooring (Series.dt.floor) the DatetimeIndex up to the daily level and indexing with the list of datetime objects using isin:

t = [pd.to_datetime('2017-07-10'), pd.to_datetime('2017-09-10')]
df.index= pd.to_datetime(df.index)

df[df.index.floor('d').isin(t)]

Output

   DateTime
2017-07-10 03:00:00     288.0
2017-07-10 04:00:00     306.0
2017-09-10 07:00:00     487.0
2017-09-10 08:00:00     523.0


来源:https://stackoverflow.com/questions/55416387/select-dataframe-rows-datetimeindex-by-a-list-of-datetime-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!