在Python Pandas DataFrame中将timedelta64 [ns]列转换为秒

Nyx*_*nyx 37 python numpy python-2.7 pandas

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]
Run Code Online (Sandbox Code Playgroud)

我尝试了以下内容

print df[:5]['duration'] / np.timedelta64(1, 's')
Run Code Online (Sandbox Code Playgroud)

但得到了错误

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
Run Code Online (Sandbox Code Playgroud)

也试过了

print df[:5]['duration'].astype('timedelta64[s]')
Run Code Online (Sandbox Code Playgroud)

但是收到了错误

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]]
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 49

这在当前版本的Pandas(版本0.14)中正常工作:

In [132]: df[:5]['duration'] / np.timedelta64(1, 's')
Out[132]: 
0    1232
1    1390
2    1495
3     797
4    1132
Name: duration, dtype: float64
Run Code Online (Sandbox Code Playgroud)

以下是旧版Pandas/NumPy的解决方法:

In [131]: df[:5]['duration'].values.view('<i8')/10**9
Out[131]: array([1232, 1390, 1495,  797, 1132], dtype=int64)
Run Code Online (Sandbox Code Playgroud)

timedelta64和datetime64数据在内部存储为8字节的整数(dtype '<i8').因此,上面将timedelta64s视为8字节的整数,然后进行整数除法,将纳秒转换为秒.

请注意,您需要使用NumPy 1.7或更高版本才能使用datetime64/timedelta64s.


wwi*_*wii 21

使用Series dt访问器可以访问datetime(timedelta)系列的方法和属性.

>>> s
0   -1 days +23:45:14.304000
1   -1 days +23:46:57.132000
2   -1 days +23:49:25.913000
3   -1 days +23:59:48.913000
4            00:00:00.820000
dtype: timedelta64[ns]
>>>
>>> s.dt.total_seconds()
0   -885.696
1   -782.868
2   -634.087
3    -11.087
4      0.820
dtype: float64
Run Code Online (Sandbox Code Playgroud)

类似日期的属性

  • 这个。它比其他答案中的语法清晰一千倍。 (4认同)

Gun*_*ach 12

刚刚意识到这是一个老线程,无论如何,如果像我这样的流浪者只点击搜索引擎上的前5个结果并最终在这里,就离开它.

确保您的类型正确无误.

  • 如果要将datetime转换为,只需将datetime对象的每小时,分钟和秒的秒数相加,如果它在一个日期内的持续时间.

      • 小时 - 小时x 3600 =秒
      • 分钟 - 分钟x 60 =秒
      • 秒 - 秒

linear_df['duration'].dt.hour*3600 + linear_df['duration'].dt.minute*60 + linear_df['duration'].dt.second

  • 如果你想将timedelta转换为秒,请使用下面的一个.

linear_df[:5]['duration'].astype('timedelta64[s]')

我让它像这样工作:

start_dt和end_dt列采用以下格式:

import datetime

linear_df[:5]['start_dt']

0   1970-02-22 21:32:48.000
1   2016-12-30 17:47:33.216
2   2016-12-31 09:33:27.931
3   2016-12-31 09:52:53.486
4   2016-12-31 10:29:44.611
Name: start_dt, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)

我的持续时间是timedelta64 [ns]格式,即减去开始结束日期时间值.

linear_df['duration'] = linear_df['end_dt'] - linear_df['start_dt']
Run Code Online (Sandbox Code Playgroud)

结果持续时间列如下所示

linear_df[:5]['duration']

0          0 days 00:00:14
1   2 days 17:44:50.558000
2   0 days 15:37:28.418000
3   0 days 18:45:45.727000
4   0 days 19:21:27.159000
Name: duration, dtype: timedelta64[ns]
Run Code Online (Sandbox Code Playgroud)

使用pandas我在两个日期之间的持续时间为float.之后更容易比较或过滤您的持续时间.

linear_df[:5]['duration'].astype('timedelta64[s]')

0        14.0
1    236690.0
2     56248.0
3     67545.0
4     69687.0
Name: duration, dtype: float64
Run Code Online (Sandbox Code Playgroud)

在我的情况下,如果我想获得超过1秒的所有持续时间.

希望能帮助到你.


Ant*_*neP 7

使用“total_seconds()”函数:

df['durationSeconds'] = df['duration'].dt.total_seconds()
Run Code Online (Sandbox Code Playgroud)