将秒数列转换为hh:mm:ss-熊猫

时间:2019-05-03 03:22:13

标签: python pandas timedelta

我确定这是在SO中,但是我似乎找不到它。我正在尝试将select t.id,j.* from mytable t cross join jsonb_array_elements_text(cola) as j(val) where j.val IN ( 'postgresql','mysql'); 中的column转换为显示为floats的{​​{1}}。以下是我的尝试:

timestamps

预期输出:

hh:mm:ss

3 个答案:

答案 0 :(得分:3)

import pandas as pd

d = ({
    'A' : [100.4,200.2,300.3,400.6,500.8,600.9],                 
    'B' : [10.4,21.5,36.3,44.3,56.6,60.5],                                      
     })

df = pd.DataFrame(data = d)

df['A'] = df['A'].astype('float64') 
df['B'] = df['B'].astype('float64') 

df['A'] = pd.to_datetime(df["A"], unit='s').dt.strftime("%H:%M:%S")
df['B'] = pd.to_datetime(df["B"], unit='s').dt.strftime("%H:%M:%S")

输出为:


    A           B
0   00:01:40    00:00:10
1   00:03:20    00:00:21
2   00:05:00    00:00:36
3   00:06:40    00:00:44
4   00:08:20    00:00:56
5   00:10:00    00:01:00

答案 1 :(得分:3)

round + pd.to_timedelta,指定单位:

df.round().apply(pd.to_timedelta, unit='s')

         A        B
0 00:01:40 00:00:10
1 00:03:20 00:00:22
2 00:05:00 00:00:36
3 00:06:41 00:00:44
4 00:08:21 00:00:57
5 00:10:01 00:01:00

A    timedelta64[ns]
B    timedelta64[ns]
dtype: object

您现在有了timedeltas功能

答案 2 :(得分:1)

另一种单线解决方案:

df = df.apply(lambda x: pd.to_datetime(x, unit='s').dt.strftime('%H:%M:%S'))

applypd.to_datetimedt.strftime一起使用。

现在:

print(df)

是:

          A         B
0  00:01:40  00:00:10
1  00:03:20  00:00:21
2  00:05:00  00:00:36
3  00:06:40  00:00:44
4  00:08:20  00:00:56
5  00:10:00  00:01:00