我正在尝试根据列表选择数据帧中的某些行。如果您将数据帧的索引设置为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] = ...发布于 2020-03-21 22:33:44
问题是您有一个datetime索引,但您尝试使用字符串(它不包含字符串)从其中进行选择。
您必须向.loc选择方法提供datetime对象的列表。Pd.to_datetime(日期列表)完成此工作:
example_df.loc[pd.to_datetime(['2018-12-12', '2018-12-05'])]请记住,您只能通过向所选内容提供列表来选择列:
example_df[['2018-12-12', '2018-12-05']]所以你会得到一个错误,因为没有这样的列...
https://stackoverflow.com/questions/58643077
复制相似问题