如何使用pandas按组计算时差?

How to calculate time difference by group using pandas?

问题

我想按组计算diff。而且我不知道如何对 time 列进行排序,以便每组结果都排序并且是积极的。

原始数据:

In [37]: df 
Out[37]:
  id                time
0  A 2016-11-25 16:32:17
1  A 2016-11-25 16:36:04
2  A 2016-11-25 16:35:29
3  B 2016-11-25 16:35:24
4  B 2016-11-25 16:35:46

我想要的结果

Out[40]:
   id   time
0  A   00:35
1  A   03:12
2  B   00:22

注意:time col的类型是timedelta64[ns]

正在尝试

In [38]: df['time'].diff(1)
Out[38]:
0                 NaT
1            00:03:47
2   -1 days +23:59:25
3   -1 days +23:59:55
4            00:00:22
Name: time, dtype: timedelta64[ns]

没有得到想要的结果。

希望

不仅解决了问题,而且代码可以运行快速,因为有 5000 万行。

您可以使用 sort_values with groupby and aggregating diff:

df['diff'] = df.sort_values(['id','time']).groupby('id')['time'].diff()
print (df)
  id                time     diff
0  A 2016-11-25 16:32:17      NaT
1  A 2016-11-25 16:36:04 00:00:35
2  A 2016-11-25 16:35:29 00:03:12
3  B 2016-11-25 16:35:24      NaT
4  B 2016-11-25 16:35:46 00:00:22

如果需要删除列 diff 中带有 NaT 的行,请使用 dropna:

df = df.dropna(subset=['diff'])
print (df)
  id                time     diff
2  A 2016-11-25 16:35:29 00:03:12
1  A 2016-11-25 16:36:04 00:00:35
4  B 2016-11-25 16:35:46 00:00:22

您也可以覆盖列:

df.time = df.sort_values(['id','time']).groupby('id')['time'].diff()
print (df)
  id     time
0  A      NaT
1  A 00:00:35
2  A 00:03:12
3  B      NaT
4  B 00:00:22

df.time = df.sort_values(['id','time']).groupby('id')['time'].diff()
df = df.dropna(subset=['time'])
print (df)
  id     time
1  A 00:00:35
2  A 00:03:12
4  B 00:00:22