我有一个日期和时间的数据框列:
0 2017-06-24 08:37:00
1 2017-06-24 08:40:00
2 2017-06-24 08:42:01
3 2017-06-24 08:44:01
4 2017-06-24 08:46:00
5 2017-06-24 08:48:00
6 2017-06-24 08:50:01
7 2017-06-24 08:52:01
8 2017-06-24 08:54:01
9 2017-06-24 08:56:00
10 2017-06-24 08:58:01
11 2017-06-24 09:00:01
12 2017-06-24 09:04:01
13 2017-06-24 09:06:01
Name: Datetime, dtype: datetime64[ns]
我想要两个时间戳的时差,例如:
2017-06-24 08:40:00 - 2017-06-24 08:37:00 = 3.0
2017-06-24 08:42:01 - 2017-06-24 08:40:00 = 2.1
我试过这段代码:
for z in range(len(df)):
abc = (df["Datetime"].iat[z+1] - df["Datetime"].iat[z])
我输出的结果是错误的:
0 days 00:03:00
0 days 00:02:01
0 days 00:02:00
0 days 00:01:59
0 days 00:02:00
0 days 00:02:01
0 days 00:02:00
0 days 00:02:00
0 days 00:01:59
0 days 00:02:01
IndexError: index 14 is out of bounds for axis 0 with size 14
预期产出:
3.0
2.1
2.0
1.59
任何帮助都将不胜感激。
答案 0 :(得分:0)
您需要diff
- 输出为timedelta
s,因此需要按total_seconds
转换,如果需要以分钟为单位输出除以60
:
df['diff'] = df['Datetime'].diff().dt.total_seconds().div(60)
print (df)
Datetime diff
0 2017-06-24 08:37:00 NaN
1 2017-06-24 08:40:00 3.000000
2 2017-06-24 08:42:01 2.016667
3 2017-06-24 08:44:01 2.000000
4 2017-06-24 08:46:00 1.983333
5 2017-06-24 08:48:00 2.000000
6 2017-06-24 08:50:01 2.016667
7 2017-06-24 08:52:01 2.000000
8 2017-06-24 08:54:01 2.000000
9 2017-06-24 08:56:00 1.983333
10 2017-06-24 08:58:01 2.016667
11 2017-06-24 09:00:01 2.000000
12 2017-06-24 09:04:01 4.000000
13 2017-06-24 09:06:01 2.000000