Python 通过DateTimeIndex在pandas数据帧中进行多重选择

Python 通过DateTimeIndex在pandas数据帧中进行多重选择,python,pandas,dataframe,datetimeindex,Python,Pandas,Dataframe,Datetimeindex,我试图根据列表选择数据框中的某些行。如果将数据帧的索引设置为DatetimeIndex,则可以通过以下方式进行选择: example_df['2018-12-12'] 但您不能像这样选择多个日期: example_df[['2018-12-12', '2018-12-05']] 我知道我可以执行以下操作,但我不想键入整个列表,以防列表更长: example_df['2018-12-12'] & example_df['2018-12-05'] & ... 另外,我知道我可以

我试图根据列表选择数据框中的某些行。如果将数据帧的索引设置为DatetimeIndex,则可以通过以下方式进行选择:

example_df['2018-12-12']
但您不能像这样选择多个日期:

example_df[['2018-12-12', '2018-12-05']]
我知道我可以执行以下操作,但我不想键入整个列表,以防列表更长:

example_df['2018-12-12'] & example_df['2018-12-05'] & ...
另外,我知道我可以使用
isin()
方法,但我想利用pandas中的原生日期选择器,因为我相信它更快

代码如下:

genesis_block_date = pd.to_datetime('01/03/2009 18:15:05 GMT')
end_date = pd.to_datetime('01/03/2029')

# Halving dates
halving_dates = ['November 28, 2012', 'July 9th, 2016', '14 May, 2020']
halving_dates = pd.to_datetime(halving_dates)

approx_block_gen_time = pd.to_timedelta('10m')
date_range = pd.date_range(start=genesis_block_date, end=end_date, freq=approx_block_gen_time)

columns = ['days_until_halving']
df_new_features = pd.DataFrame(index=date_range, columns=columns)
df_new_features[halving_dates] = ...

问题是您有一个datetime索引,但您试图使用字符串(它不包含字符串)从中进行选择

必须向.loc[]选择方法提供日期时间对象列表。pd.to_datetime([日期列表])完成此任务:

example_df.loc[pd.to_datetime(['2018-12-12', '2018-12-05'])]
请记住,您只能通过提供列表来选择列:

example_df[['2018-12-12', '2018-12-05']]

所以您得到了一个错误,因为没有这样的列…

非常感谢,它成功了。我不知道为什么,但很明显.loc期望的是相同的对象类型(我指的是索引类型)。但有趣的是,正如我在OP:example_df['2018-12-12']中所说,常规选择器只接受一个日期