计算用户的时间增量

问题描述 投票:1回答:2

我有用户会话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_ids,如下所示:

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

怎么计算这个?

python pandas datetime
2个回答
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转换timedeltas:

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
投票

你可以将qazxsw poi与qazxsw poi结合使用并减去qazxsw poi:

groupby

很快:

apply
© www.soinside.com 2019 - 2024. All rights reserved.