Python Pandas - 如何将字符串HH:MM:SS.mmm转换为float sss.ms?

时间:2018-03-15 05:57:47

标签: python pandas datetime type-conversion floating-point-conversion

我想将字符串值HH:MM:SS.mmm转换为浮点值sec.milliseconds进行算术运算。有没有直接的方法来做到这一点,因为我现在通过分割字符串功能这样做,这是一个非常繁琐的过程。 Dataframe看起来像:

Col1
00:00:05.063
00:01:00.728
00:03:10.117

输出应该看起来像

  5.063
 60.728
190.117

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

将您的列转换为timedelta,然后转换为int(将结果返回到ns,除以1e9以获得秒数):

pd.to_timedelta(df.Col1).astype(int) / 1e9

0      5.063
1     60.728
2    190.117
Name: Col1, dtype: float64

答案 1 :(得分:1)

使用to_timedelta + total_seconds

df['Col1'] = pd.to_timedelta(df['Col1']).dt.total_seconds()
print (df)
      Col1
0    5.063
1   60.728
2  190.117

答案 2 :(得分:0)

df['HourandMinute'] = df['Dayandtime_call'].dt.hour + \
    df['Dayandtime_call'].dt.minute / 100