如何按时间对pandas时间序列进行子集化

时间:2014-02-07 10:53:44

标签: python pandas

我正在尝试按时间跨越多天的大熊猫时间序列。例如,我只想要在12:00到13:00之间的时间。

我知道如何在特定日期执行此操作,例如,

In [44]: type(test)
Out[44]: pandas.core.frame.DataFrame

In [23]: test
Out[23]:
                           col1
timestamp
2012-01-14 11:59:56+00:00     3
2012-01-14 11:59:57+00:00     3
2012-01-14 11:59:58+00:00     3
2012-01-14 11:59:59+00:00     3
2012-01-14 12:00:00+00:00     3
2012-01-14 12:00:01+00:00     3
2012-01-14 12:00:02+00:00     3

In [30]: test['2012-01-14 12:00:00' : '2012-01-14 13:00']
Out[30]:
                           col1
timestamp 
2012-01-14 12:00:00+00:00     3
2012-01-14 12:00:01+00:00     3
2012-01-14 12:00:02+00:00     3

但是我使用test.index.hourtest.index.indexer_between_time()的任何日期都没有这样做,这些日期都被建议作为类似问题的答案。我尝试了以下方法:

In [44]: type(test)
Out[44]: pandas.core.frame.DataFrame

In [34]: test[(test.index.hour >= 12) & (test.index.hour < 13)]
Out[34]:
Empty DataFrame
Columns: [col1]
Index: []

In [36]: import datetime as dt
In [37]: test.index.indexer_between_time(dt.time(12),dt.time(13))
Out[37]: array([], dtype=int64)

对于第一种方法,我不知道test.index.hourtest.index.minute实际返回的是什么:

In [41]: test.index
Out[41]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-14 11:59:56, ..., 2012-01-14 12:00:02]
Length: 7, Freq: None, Timezone: tzlocal()

In [42]: test.index.hour
Out[42]: array([11, 23,  0,  0,  0,  0,  0], dtype=int32)

In [43]: test.index.minute
Out[43]: array([59, 50,  0,  0, 50, 50,  0], dtype=int32)

他们回来了什么?如何进行所需的子集化?理想情况下,我如何才能使上述两种方法都起作用?

编辑:问题结果是索引无效,上面的Timezone: tzlocal()证明了这一点,因为tzlocal()不应该被允许作为时区。当我将生成索引的方法更改为pd.to_datetime()时,根据接受答案的最后部分,一切都按预期工作。

1 个答案:

答案 0 :(得分:10)

假设索引是有效的pandas时间戳,以下内容将起作用:

test.index.hour返回一个数组,其中包含数据框中每行的小时数。例如:

df = pd.DataFrame(randn(100000,1),columns=['A'],index=pd.date_range('20130101',periods=100000,freq='T'))

df.index.year返回array([2013, 2013, 2013, ..., 2013, 2013, 2013])

要抓住时间介于12和1之间的所有行,请使用

df.between_time('12:00','13:00')

这将在几天/几年内获取该时间范围等。如果索引不是有效时间戳,请使用pd.to_datetime()将其转换为有效时间戳

相关问题