如何按一天中的时间细分熊猫时间序列
问题内容:
我正在尝试将一个熊猫时间序列的子集划分为一天中的多个天。例如,我只想要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.hour
或test.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.hour
或test.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()
根据接受的答案的最后一部分将生成索引的方法更改为时,一切都按预期工作。
问题答案:
假设索引是有效的熊猫时间戳记,则将执行以下操作:
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()