【发布时间】:2014-09-04 18:13:11
【问题描述】:
我有一个带有 datetimeindex 的 pandas 数据框。我想创建一个包含经过时间的列。我是这样计算的:
startTime = df.index[0]
elapsed = df.index - startTime
结果:
TypeError Traceback (most recent call last)
<ipython-input-56-279fd541b1e2> in <module>()
----> 1 df.index - startTime
C:\Python27\lib\site-packages\pandas\tseries\index.pyc in __sub__(self, other)
612 return self.shift(-other)
613 else: # pragma: no cover
--> 614 raise TypeError(other)
615
616 def _add_delta(self, delta):
TypeError: 2014-07-14 14:47:57
奇怪的是,例如:
df.index[1] - startTime
返回:
datetime.timedelta(0, 1)
我认为可能是因为它是一个日期时间索引而不是一个导致问题的普通系列。但是,当我第一次使用 df.index 作为数据参数创建一个新系列然后尝试减法时,我收到一大堆警告,说我隐式转换了两种不兼容的类型,并且它在未来将不起作用:
timeStamps =pd.Series(data=df.index)
elapsed = timeStamps - timeStamps[0]
返回
C:\Python27\lib\site-packages\pandas\core\format.py:1851: DeprecationWarning: Implicitly casting between incompatible kinds. In a future numpy release, this will raise an error. Use casting="unsafe" if this is intentional.
elif format_short and x == 0:
虽然我确实使用后一种方法得到了正确的一系列 TimeDelta,但我不喜欢依赖已弃用的代码。是否有“正确”的方法来计算经过的时间?
这是我从中获取数据的 csv 文件的一部分:
Timestamp Bubbler_Temperature_Setpoint
14-7-2014 14:47:57 13.000000
14-7-2014 14:47:58 13.000000
14-7-2014 14:47:59 13.000000
14-7-2014 14:48:00 13.000000
14-7-2014 14:48:01 13.000000
14-7-2014 14:48:02 13.000000
14-7-2014 14:48:03 13.000000
14-7-2014 14:48:04 13.000000
14-7-2014 14:48:05 13.000000
我使用“read_csv”函数将其读入数据帧:
df = pd.read_csv('test.csv',sep='\t',parse_dates='Timestamp',index_col='Timestamp')
我使用的是熊猫版本 0.13.1
【问题讨论】:
-
请提供示例数据框
-
显示你的 pandas/numpy 版本
-
我已经用您要求的信息编辑了我的问题