Convert timedelta64[ns] column to seconds in Python Pandas DataFrame

后端 未结 5 1617
借酒劲吻你
借酒劲吻你 2020-11-28 06:54

A pandas DataFrame column duration contains timedelta64[ns] as shown. How can you convert them to seconds?

0   00:20:32
1   00:23:1         


        
5条回答
  •  抹茶落季
    2020-11-28 07:18

    This works properly in the current version of Pandas (version 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
    

    Here is a workaround for older versions of Pandas/NumPy:

    In [131]: df[:5]['duration'].values.view('

    timedelta64 and datetime64 data are stored internally as 8-byte ints (dtype '). So the above views the timedelta64s as 8-byte ints and then does integer division to convert nanoseconds to seconds.

    Note that you need NumPy version 1.7 or newer to work with datetime64/timedelta64s.

提交回复
热议问题