计算用户的时间增量

时间:2019-03-30 18:47:01

标签: python pandas datetime

我有用户会话ID和发生某些事件的会话ID的时间戳。我想计算第一个事件和最后一个事件之间的时间。请参见下面的示例:

session_id   timestamp
sess1        2018-11-05 14:28:25.260
sess2        2018-11-04 12:14:59.576
sess2        2018-11-04 11:55:00.584
sess2        2018-11-04 12:16:44.702
sess3        2018-11-04 12:04:37.419

我想计算sess2的第一个时间戳和最后一个时间戳之间的差,以及所有其他类似的session_id,如下所示:

session_id   timeSpent
sess1        1
sess2        125 (for example)        
sess3        1

如何计算?

2 个答案:

答案 0 :(得分:2)

使用:

#convert column to datetimes if necessary
df['timestamp'] = pd.to_datetime(df['timestamp'])

#aggregate min and max
df1 = df.groupby('session_id')['timestamp'].agg(['min','max'])
#subtract to new column
df1['timeSpent'] = df1.pop('max') - df1.pop('min')
df1 = df1.reset_index()
print (df1)
  session_id       timeSpent
0      sess1        00:00:00
1      sess2 00:21:44.118000
2      sess3        00:00:00

带有GroupBy.agg和元组的单行解决方案:

df1 = (df.groupby('session_id')['timestamp']
        .agg([('timeSpent', lambda x: x.max() - x.min())])
        .reset_index())
print (df1)
  session_id       timeSpent
0      sess1        00:00:00
1      sess2 00:21:44.118000
2      sess3        00:00:00

如果需要以秒为单位输出,请用Series.dt.total_seconds转换时间增量:

df1['timeSpent'] = (df1.pop('max') - df1.pop('min')).dt.total_seconds()
df1 = df1.reset_index()
print (df1)
  session_id  timeSpent
0      sess1      0.000
1      sess2   1304.118
2      sess3      0.000

单行解决方案:

df1 = (df.groupby('session_id')['timestamp']
        .agg([('timeSpent', lambda x: x.max() - x.min())])
        .assign(timeSpent = lambda x: x['timeSpent'].dt.total_seconds())
        .reset_index())
print (df1)
  session_id  timeSpent
0      sess1      0.000
1      sess2   1304.118
2      sess3      0.000

答案 1 :(得分:1)

您可以将groupbyapply结合使用并减去max - min

df1 = df.groupby('session_id').timestamp.apply(lambda x: x.max() - x.min()).reset_index()

df1.rename({'timestamp':'timeSpent'},axis=1,inplace=True)

print(df1)
  session_id       timeSpent
0      sess1        00:00:00
1      sess2 00:21:44.118000
2      sess3        00:00:00

以秒为单位:

df1 = df.groupby('session_id').timestamp.apply(lambda x: x.max() - x.min()).reset_index()
df1.rename({'timestamp':'timeSpent'},axis=1,inplace=True)
df1['timeSpent'] = df1['timeSpent'].dt.total_seconds()

print(df1)
  session_id  timeSpent
0      sess1      0.000
1      sess2   1304.118
2      sess3      0.000