Python 熊猫:使用DateTimeIndex列表从DataFrame中提取多行
我有一个熊猫数据帧,索引如下,频率为秒:Python 熊猫:使用DateTimeIndex列表从DataFrame中提取多行,python,pandas,dataframe,indexing,Python,Pandas,Dataframe,Indexing,我有一个熊猫数据帧,索引如下,频率为秒: 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
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.loc[['2015-12-28 08:32:39', '2015-12-28 08:32:48']]
但我得到了以下错误:
KeyError: "None of [['2015-12-28 08:32:39', '2015-12-28 08:32:48']] are in the [index]"
您可以通过或将
列表
转换为日期时间
:
或:
样本:
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
print (df.loc[pd.to_datetime(d)])
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