我需要计算时间差,然后从第一行开始分配结果。 这是我的代码:
import pandas as pd
dtime = pd.DataFrame({'letter': ['a', 'b', 'c', 'd', 'e', 'f'], 'time': ['19/11/2019 06:02:39', '19/11/2019 06:32:39', '2019-11-19 06:42:39' , '19/11/2019 06:52:39', '19/11/2019 07:02:39', '19/11/2019 07:12:39']})
dtime['time'] = pd.to_datetime(dtime['time'])
dtime['Time_diff']=(dtime['time']-dtime['time'].shift()).fillna(0)
print (dtime)
dtime.to_excel('test_time.xlsx', 'Sheet1', index=True)
这是输出:
letter time Time_diff
0 a 2019-11-19 06:02:39 00:00:00
1 b 2019-11-19 06:32:39 00:30:00
2 c 2019-11-19 06:42:39 00:10:00
3 d 2019-11-19 06:52:39 00:10:00
4 e 2019-11-19 07:02:39 00:10:00
5 f 2019-11-19 07:12:39 00:10:00
但是我需要这样:
letter time Time_diff
0 a 2019-11-19 06:02:39 00:30:00
1 b 2019-11-19 06:32:39 00:10:00
2 c 2019-11-19 06:42:39 00:10:00
3 d 2019-11-19 06:52:39 00:10:00
4 e 2019-11-19 07:02:39 00:10:00
5 f 2019-11-19 07:12:39 00:00:00
行0:0 a 2019-11-19 06:02:39 00:30:00
有可能吗?
答案 0 :(得分:2)
更改顺序并将-1
添加到Series.shift
,对于替换缺少的值,请使用0 timedelta
:
dtime['Time_diff']=(dtime['time'].shift(-1)-time['time']).fillna(pd.Timedelta(0))
print (dtime)
letter time Time_diff
0 a 2019-11-19 06:02:39 00:30:00
1 b 2019-11-19 06:32:39 00:10:00
2 c 2019-11-19 06:42:39 00:10:00
3 d 2019-11-19 06:52:39 00:10:00
4 e 2019-11-19 07:02:39 00:10:00
5 f 2019-11-19 07:12:39 00:00:00