我是Python新手,至少可以看到5 similar questions,而这一个是very close,但它们中没有一个适合我
我有一个非唯一客户的数据框架
customer_id amount male age income days reward difficulty duration
0 id_1 16.06 1 45 62000.0 608 2.0 10.0 10.0
1 id_1 18.00 1 45 62000.0 608 2.0 10.0 10.0
我试图按customer_id
对它们进行分组,按amount
求和,保留所有其他列,再加上一列total
,计算我的交易
期望输出
customer_id amount male age income days reward difficulty duration total
0 id_1 34.06 1 45 62000.0 608 2.0 10.0 10.0 2
到目前为止,我个人的最佳尝试并没有保留所有列
groupby('customer_id')['amount'].agg(total_sum = 'sum', total = 'count')
基于@Scott Boston的回答,我自己也找到了答案,我承认我的解决方案并不优雅(也许有什么东西可以帮助清理它)。但当我有非唯一行(例如,每个
customer_id
有五个不同的事务)时,它为我提供了一个扩展的解决方案我的输出是
您可以这样做,包括groupby中的所有其他列,然后在聚合后重置索引:
输出:
你可以做:
相关问题 更多 >
编程相关推荐