用于重新采样计算的Python tz感知str到datetime对象


  • 我有下面的tz感知字符串
  • 我想对此数据使用data.resample('D'(操作
  • 我很难把它转换成正确的格式。我尝试过使用pd.to_datetime,但在尝试使用重采样时出现以下错误

TypeError:仅对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但获得了"Index"的实例

>>> test1['timestamp']
0        2017-01-03 08:30:00-06:00
1        2017-01-03 08:30:32-06:00
2        2017-01-03 08:30:42-06:00
3        2017-01-03 08:30:46-06:00
4        2017-01-03 08:30:52-06:00
...            
65334    2017-12-29 14:55:02-06:00
65335    2017-12-29 14:55:26-06:00
65336    2017-12-29 14:55:54-06:00
65337    2017-12-29 14:59:23-06:00
65338    2017-12-29 14:59:46-06:00
Name: timestamp, Length: 65339, dtype: object

实现这一目标的最佳方法是什么?

谢谢

您的错误消息以开头,仅对DatetimeIndex有效

因此,在将时间戳列转换为日期时间后,创建aDatetimeIndex(并保存以备将来使用(:

ind = pd.DatetimeIndex(pd.to_datetime(df.timestamp))

结果是:

DatetimeIndex(['2017-01-03 08:30:00-06:00', '2017-01-03 08:30:32-06:00',
'2017-01-03 08:30:42-06:00', '2017-01-03 08:30:46-06:00',
'2017-01-03 08:30:52-06:00'],
dtype='datetime64[ns, pytz.FixedOffset(-360)]', name='timestamp', freq=None)

或者,您应该在DataFrame中设置索引,基于上述公式的

wrk = df.set_index(pd.DatetimeIndex(pd.to_datetime(df.timestamp)))
.drop(columns=['timestamp'])

然后重新对其进行索引(具有某种聚合功能(,例如:

wrk.resample('15s').sum()

我将源df创建为:

timestamp  amount
0  2017-01-03 08:30:00-06:00      12
1  2017-01-03 08:30:32-06:00      14
2  2017-01-03 08:30:42-06:00      17
3  2017-01-03 08:30:46-06:00      19
4  2017-01-03 08:30:52-06:00      23

得到以下结果:

amount
timestamp                        
2017-01-03 08:30:00-06:00      12
2017-01-03 08:30:15-06:00       0
2017-01-03 08:30:30-06:00      31
2017-01-03 08:30:45-06:00      42

最新更新