【发布时间】:2014-12-14 21:56:55
【问题描述】:
如图所示,pandas DataFrame 列 duration 包含 timedelta64[ns]。如何将它们转换为秒?
0 00:20:32
1 00:23:10
2 00:24:55
3 00:13:17
4 00:18:52
Name: duration, dtype: timedelta64[ns]
我尝试了以下
print df[:5]['duration'] / np.timedelta64(1, 's')
但出现错误
Traceback (most recent call last):
File "test.py", line 16, in <module>
print df[0:5]['duration'] / np.timedelta64(1, 's')
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 130, in wrapper
"addition and subtraction, but the operator [%s] was passed" % name)
TypeError: can only operate on a timedeltas for addition and subtraction, but the operator [__div__] was passed
也试过了
print df[:5]['duration'].astype('timedelta64[s]')
但收到错误
Traceback (most recent call last):
File "test.py", line 17, in <module>
print df[:5]['duration'].astype('timedelta64[s]')
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 934, in astype
values = com._astype_nansafe(self.values, dtype)
File "C:\Python27\lib\site-packages\pandas\core\common.py", line 1653, in _astype_nansafe
raise TypeError("cannot astype a timedelta from [%s] to [%s]" % (arr.dtype,dtype))
TypeError: cannot astype a timedelta from [timedelta64[ns]] to [timedelta64[s]]
【问题讨论】:
-
这是已修复的最新版本;与source code 一样,如果两边都是timedelta 加法,则支持减法和除法。该部分代码在 2013 年被更改
-
@behzad.nouri 是对的,我相信这是在 > 0.13.1 中修复的(可能需要 0.14),但当前是 0.15.0:pandas.pydata.org/pandas-docs/stable/…
-
@behzad.nouri 谢谢,更新到 Pandas 0.15.0 和 numpy 1.9.0 让它工作。
标签: python python-2.7 numpy pandas