我有一段时间像这样
df = pd.DataFrame({'times':['10:59:20.1647', '11:05:46.2258', '11:10:59.4658']})
我的目标是第一次减去所有这些时间。为此,我将列转换为datetime.time
类型并将第一个值减去所有列:
pd.to_datetime(df['times']).dt.time - pd.to_datetime(df['times']).dt.time.iloc[0]
然而,通过这样做,我收到一个错误:
TypeError: unsupported operand type(s) for -: 'datetime.time' and'datetime.time'
为了实现我的目标,你能否建议一种聪明而优雅的方式?
答案 0 :(得分:1)
使用timedeltas
:
a = pd.to_timedelta(df['times'])
b = a - a.iat[0]
print (b)
0 00:00:00
1 00:06:26.061100
2 00:11:39.301100
Name: times, dtype: timedelta64[ns]
如果需要时间:
c = pd.to_datetime(b).dt.time
print (c)
0 00:00:00
1 00:06:26.061100
2 00:11:39.301100
Name: times, dtype: object
print (c.apply(type))
0 <class 'datetime.time'>
1 <class 'datetime.time'>
2 <class 'datetime.time'>
Name: times, dtype: object
输出timedelta
的另一种解决方案:
a = pd.to_datetime(df['times'])
b = a - a.iat[0]
print (b)
0 00:00:00
1 00:06:26.061100
2 00:11:39.301100
Name: times, dtype: timedelta64[ns]