pandas ,python - 如何在时间序列中选择特定时间 [英] pandas, python - how to select specific times in timeseries

查看:24
本文介绍了 pandas ,python - 如何在时间序列中选择特定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在使用 Python 和 Pandas 分析了一组每小时的数据已经工作了很长时间,发现它非常好(来自 Matlab.)

I worked now for quite some time using python and pandas for analysing a set of hourly data and find it quite nice (Coming from Matlab.)

现在我有点卡住了.我像这样创建了我的 DataFrame:

Now I am kind of stuck. I created my DataFrame like that:

SamplingRateMinutes=60
index = DateRange(initialTime,finalTime, offset=datetools.Minute(SamplingRateMinutes))
ts=DataFrame(data, index=index)

我现在要做的是在10到13点和20-23点选择所有天的数据,以使用这些数据进行进一步的计算.到目前为止,我使用

What I want to do now is to select the Data for all days at the hours 10 to 13 and 20-23 to use the data for further calculations. So far I sliced the data using

 selectedData=ts[begin:end]

而且我肯定会得到某种脏循环来选择所需的数据.但是必须有一种更优雅的方式来准确地索引我想要的东西.我确信这是一个常见问题,伪代码中的解决方案应该看起来像这样:

And I am sure to get some kind of dirty looping to select the data needed. But there must be a more elegant way to index exacly what I want. I am sure this is a common problem and the solution in pseudocode should look somewhat like that:

myIndex=ts.index[10<=ts.index.hour<=13 or 20<=ts.index.hour<=23]
selectedData=ts[myIndex]

更何况我是一名工程师而不是程序员:) ...然而

To mention I am an engineer and no programer :) ... yet

推荐答案

这是一个可以满足您要求的示例:

Here's an example that does what you want:

In [32]: from datetime import datetime as dt

In [33]: dr = p.DateRange(dt(2009,1,1),dt(2010,12,31), offset=p.datetools.Hour())

In [34]: hr = dr.map(lambda x: x.hour)

In [35]: dt = p.DataFrame(rand(len(dr),2), dr)

In [36]: dt 

Out[36]: 
<class 'pandas.core.frame.DataFrame'>
DateRange: 17497 entries, 2009-01-01 00:00:00 to 2010-12-31 00:00:00
offset: <1 Hour>
Data columns:
0    17497  non-null values
1    17497  non-null values
dtypes: float64(2)

In [37]: dt[(hr >= 10) & (hr <=16)]

Out[37]: 
<class 'pandas.core.frame.DataFrame'>
Index: 5103 entries, 2009-01-01 10:00:00 to 2010-12-30 16:00:00
Data columns:
0    5103  non-null values
1    5103  non-null values
dtypes: float64(2)

这篇关于 pandas ,python - 如何在时间序列中选择特定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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