Pandas:使用DatetimeIndices列表从DataFrame中提取多行 [英] Pandas: extracting multiple rows from DataFrame with list of DatetimeIndices

查看:2107
本文介绍了Pandas:使用DatetimeIndices列表从DataFrame中提取多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下索引的pandas Dataframe,其频率为秒:

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']]

但是我收到以下错误:

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


推荐答案

您可以通过列表转换为 datetime //pandas.pydata.org/pandas-docs/stab le / generated / pandas.DatetimeIndex.htmlrel =nofollow noreferrer> DatetimeIndex to_datetime

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)])

或:

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

这篇关于Pandas:使用DatetimeIndices列表从DataFrame中提取多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆