Pandas: extracting multiple rows from DataFrame with list of DatetimeIndices

五迷三道 提交于 2019-12-23 22:07:24

问题


I have a pandas Dataframe with the following index with seconds frequency:

DatetimeIndex(['2015-12-28 05:20:05', '2015-12-28 05:20:06',
               '2015-12-28 05:20:07', '2015-12-28 05:20:08',
               ...
               '2015-12-28 21:19:55', '2015-12-28 21:19:56',
               '2015-12-28 21:19:57', '2015-12-28 21:19:58']

I want to extract multiple rows at once, given a list of datetime strings. I tried:

df.loc[['2015-12-28 08:32:39', '2015-12-28 08:32:48']]

But I get the following error:

KeyError: "None of [['2015-12-28 08:32:39', '2015-12-28 08:32:48']] are in the [index]"

回答1:


You can convert list to datetime by DatetimeIndex or to_datetime:

d = ['2015-12-28 05:20:05', '2015-12-28 21:19:58']
print (df.loc[pd.DatetimeIndex(d)])

Or:

print (df.loc[pd.to_datetime(d)])

Sample:

idx = pd.DatetimeIndex(['2015-12-28 05:20:05', '2015-12-28 05:20:06',
               '2015-12-28 05:20:07', '2015-12-28 05:20:08',
               '2015-12-28 21:19:55', '2015-12-28 21:19:56',
               '2015-12-28 21:19:57', '2015-12-28 21:19:58'])
df = pd.DataFrame({'s': range(8)}, index=idx)  
print (df)
                     s
2015-12-28 05:20:05  0
2015-12-28 05:20:06  1
2015-12-28 05:20:07  2
2015-12-28 05:20:08  3
2015-12-28 21:19:55  4
2015-12-28 21:19:56  5
2015-12-28 21:19:57  6
2015-12-28 21:19:58  7

d = ['2015-12-28 05:20:05', '2015-12-28 21:19:58']
print (df.loc[pd.to_datetime(d)])
                     s
2015-12-28 05:20:05  0
2015-12-28 21:19:58  7

print (df.loc[pd.to_datetime(d)])
                     s
2015-12-28 05:20:05  0
2015-12-28 21:19:58  7


来源:https://stackoverflow.com/questions/45213834/pandas-extracting-multiple-rows-from-dataframe-with-list-of-datetimeindices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!