我有一只熊猫-
id session_id timestamp url
1 #123 1 a.com
1 #123 2 a.com
1 #123 3 b.com
1 #123 4 b.com
1 #123 5 a.com
1 #546 37 c.com
2 #342 78 b.com
2 #674 79 c.com我希望使用id对所有数据进行分组,然后使用session_id计算每个url上的总时间。
做DataFrame的代码-
pd.DataFrame({
'id':[1, 1, 1, 1, 1, 1, 2, 2],
'session_id':['#123', '#123', '#123', '#123', '#123', '#546', '#342', '#674'],
'url':['a.com', 'a.com', 'b.com', 'b.com', 'a.com', 'c.com', 'b.com', 'c.com'],
'timestamp':[1,2,3,4,5,37,78,79]
})Timespent被计算为
2(timestamp)-1(timestamp)=1(实际数据具有时间戳作为UNIX时间戳),现在对于id1和session_id#123-a.com有total_timespent as (2-1)+(5-4) =2(因为3,4时间戳用于b.com)。
预期输出-
id session_id timestamp url total_time
1 #123 1 a.com 2
1 #123 2 a.com 2
1 #123 3 b.com 2
1 #123 4 b.com 2
1 #123 5 a.com 2
1 #546 37 c.com 0
2 #342 78 b.com 0
2 #674 79 c.com 0在这里,url的时间被广播到url的所有行(如id和session_id)。
发布于 2019-11-20 12:13:34
您可以首先计算每个会话每个条目的时间差,并将其存储在一个新列time_diff中:
df['time_diff'] = df.groupby(['id', 'session_id']).diff().fillna(0) 然后,对于会话中的每个url,您可以将花在该url上的时间加起来:
df['total_time'] = df.groupby(['id', 'session_id', 'url'])['time_diff'].transform('sum')这导致了这样的输出:
id session_id url timestamp time_diff total
0 1 #123 a.com 1 0.0 2.0
1 1 #123 a.com 2 1.0 2.0
2 1 #123 b.com 3 0.0 2.0
3 1 #123 b.com 4 1.0 2.0
4 1 #123 a.com 5 1.0 2.0
5 1 #546 c.com 37 0.0 0.0
6 2 #342 b.com 78 0.0 0.0
7 2 #674 c.com 79 0.0 0.0https://stackoverflow.com/questions/58953824
复制相似问题