通过DateTimeIndex在熊猫数据框中进行多项选择

时间:2019-10-31 12:09:20

标签: 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'] & ...

我还知道我可以使用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] = ...

1 个答案:

答案 0 :(得分:0)

问题是您有一个日期时间索引,但是您尝试使用字符串(不包含它)从中进行选择。

您必须为.loc []选择方法提供日期时间对象的列表。 pd.to_datetime([日期列表])完成此工作:

example_df.loc[pd.to_datetime(['2018-12-12', '2018-12-05'])]

请记住,您只能通过提供所选内容的列表来选择列:

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

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

相关问题