Cột gấu trúc Cột DataFrame duration
chứa timedelta64[ns]
như được hiển thị. Làm thế nào bạn có thể chuyển đổi chúng thành giây?Chuyển đổi cột timedelta64 [ns] thành giây trong Python Pandas DataFrame
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]
Tôi đã thử các sau
print df[:5]['duration']/np.timedelta64(1, 's')
nhưng đã nhận lỗi
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
Cũng cố gắng
print df[:5]['duration'].astype('timedelta64[s]')
nhưng đã nhận lỗi
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]]
đây là phiên bản cố định gần đây; như trong [mã nguồn] (https://github.com/pydata/pandas/blame/778cfe43a4cef52442e00fe505290079a717f515/pandas/core/ops.py#L304), nếu cả hai bên đều được bổ sung, trừ, và _division_ theo thời gian. phần đó của mã đã được thay đổi trở lại vào năm 2013 –
@ behzad.nouri là đúng, tôi tin rằng điều này đã được sửa trong> 0.13.1 (có thể cần 0.14), nhưng hiện tại là 0.15.0: http://pandas.pydata.org /pandas-docs/stable/timedeltas.html#frequency-conversion – Jeff
@ behzad.nouri Xin cảm ơn, cập nhật lên Pandas 0.15.0 và vâng lời 1.9.0 khiến nó hoạt động. – Nyxynyx