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

2024-04-25 22:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将熊猫的时间序列细分为一天中的多个时间段。E、 我只想要12点到13点之间的时间。

我知道在某个特定的日期怎么做,例如

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()时,根据接受答案的最后一部分,一切都按预期进行了。


Tags: 方法intestdataframepandasindextime时间
1条回答
网友
1楼 · 发布于 2024-04-25 22:04:20

假设索引是有效的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()将其转换为有效的时间戳

相关问题 更多 >