问题
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