我有以下日期列表:
date_list
DatetimeIndex(['2015-07-10', '2015-07-13', '2015-07-14', '2015-07-15',
'2015-07-16', '2015-07-17', '2015-08-20', '2015-09-21',
'2015-09-22', '2015-09-23']
要访问这些日期的熊猫行的值,我这样做:
df['Close'].loc[dates_list]
这会产生以下错误:
KeyError: 'Passing list-likes to .loc or [] with any missing labels is no longer supported
如何获取这些DateTtimeindex
的行值
答案 0 :(得分:1)
像魅力一样工作:
df.loc[date_list, 'Close']
测试示例,大致基于您提供的内容-如果与您的用例相比有些不足,请随时澄清细节:
import pandas as pd
date_list=pd.DatetimeIndex(['2015-07-10', '2015-07-13', '2015-07-14', '2015-07-15',
'2015-07-16', '2015-07-17', '2015-08-20', '2015-09-21',
'2015-09-22', '2015-09-23'])
df=pd.DataFrame({'Close': list("abcdefghijklmnoprstuvwxyz"), 'dt': ['2015-07-10', '2015-07-13', '2015-07-14', '2015-07-15','2017-01-01','2017-01-03','2015-07-01','2005-09-07', '2018-02-04',
'2015-07-16', '2015-07-17', '2015-08-20', '2015-09-21','2019-04-06','2002-04-07','2002-05-19',
'2015-09-22', '2015-09-23','2020-07-07', '2020-06-08', '2018-02-01', '2000-04-04', '2001-09-09', '2008-08-03', '2008-09-01']})
df['dt']=pd.to_datetime(df['dt'])
df=df.set_index('dt')
res=df.loc[date_list, 'Close']
>>> res
2015-07-10 a
2015-07-13 b
2015-07-14 c
2015-07-15 d
2015-07-16 j
2015-07-17 k
2015-08-20 l
2015-09-21 m
2015-09-22 r
2015-09-23 s
Name: Close, dtype: object