pandas:groupby中的时间差

pandas: time difference in groupby

如何计算当前行和下一行之间每个id的时间差 以下数据集:

time                    id

2012-03-16 23:50:00      1
2012-03-16 23:56:00      1
2012-03-17 00:08:00      1
2012-03-17 00:10:00      2
2012-03-17 00:12:00      2
2012-03-17 00:20:00      2
2012-03-20 00:43:00      3

并得到下一个结果:

time                    id       tdiff
2012-03-16 23:50:00      1         6  
2012-03-16 23:56:00      1         12  
2012-03-17 00:08:00      1         NA
2012-03-17 00:10:00      2         2 
2012-03-17 00:12:00      2         8    
2012-03-17 00:20:00      2         NA 
2012-03-20 00:43:00      3         NA

我看到你需要 id 在几分钟内得到结果。方法如下:

在 groupby 中使用 diff() :

# first convert to datetime with the right format 
data['time']=pd.to_datetime(data.time, format='%Y-%m-%d %H:%M:%S')
data['tdiff']=(data.groupby('id').diff().time.values/60000000000).astype(int)
data['tdiff'][data['tdiff'] < 0] = np.nan
print(data)

输出

                 time  id  tdiff
0 2012-03-16 23:50:00   1    NaN
1 2012-03-16 23:56:00   1    6.0
2 2012-03-17 00:08:00   1   12.0
3 2012-03-17 00:10:00   2    NaN
4 2012-03-17 00:12:00   2    2.0
5 2012-03-17 00:20:00   2    8.0
6 2012-03-20 00:43:00   3    NaN