我有一个名为“客户”的表,我想显示某人根据用户 ID 注册或购买商品的次数。
目标是有一个表格,根据用户 ID 显示注册完成和购买的总和
这是我写的代码。不幸的是,并非所有列都显示
new_file= new_data.groupby(['userid'])
['Registration_Complete','Purchase'].agg('sum')
new_file.head(5)
这是我用来根据用户 ID 计算注册和购买的表格
Event_day timestamp install userid registration purchase
1/1/1900 1/1/1900 16:10 yes 555221 1 0
1/1/1900 1/1/1900 16:12 yes 555221 1 1
2/19/2010 1/19/2010 16:40 no 533211 0 1
2/19/2010 1/19/2016 16:53 yes 533211 0 1
2/20/2017 2/20/2017 15:46 yes 53200 1 0
3/15/2017 3/15/2018 15:48 yes 53200 1 0
3/15/2017 3/15/2018 20:14 yes 53200 1 0
我想要一些能给我总和的东西
Event_day timestamp install userid registration purchase
1/1/1900 1/1/1900 16:10 yes 555221 2 0
2/19/2010 1/19/2016 16:53 yes 533211 0 2
3/15/2017 3/15/2018 20:14 yes 53200 5 0
最佳答案
IIUC您可以保留其他列的first
或last
值,将字典传递给agg
agg = {'Event_day': 'last', 'timestamp': 'last', 'install': 'last', 'registration': 'sum', 'purchase': 'sum'}
df.groupby('userid').agg(agg).reset_index()
userid Event_day timestamp install registration purchase
0 53200 3/15/2017 3/15/2018 20:14 yes 3 0
1 533211 2/19/2010 1/19/2016 16:53 yes 0 2
2 555221 1/1/1900 1/1/1900 16:12 yes 2 1
编辑:
请记住,有几个答案可能是正确的,我发现在它们之间进行性能测试很有趣
时间
dfg1 = df.groupby("userid")["install", "timestamp", "Event_day"].max()
dfg2 = df.groupby("userid").sum()
pd.concat([dfg1, dfg2], axis=1)
38.5 ms ± 393 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
first_other_columns = df[['Event_day', 'timestamp', 'install', 'userid']].drop_duplicates(['userid'], keep='first')
grouped = df.groupby(['userid']).sum().reset_index()
pd.merge(grouped, first_other_columns, on=['userid'])
11.3 ms ± 100 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
agg = {'Event_day': 'last', 'timestamp': 'last', 'install': 'last', 'registration': 'sum', 'purchase': 'sum'}
df.groupby('userid').agg(agg).reset_index()
6.85 ms ± 62.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
关于pandas - 在pandas中使用groupby或aggregate的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909708/