Groupby和sum by 1列,保留所有其他列,并变异一个新列,使用Pandas计数求和的行

2024-05-13 20:44:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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')

enter image description here


Tags: idagecustomerdaysamountmaletotalquestions
3条回答

基于@Scott Boston的回答,我自己也找到了答案,我承认我的解决方案并不优雅(也许有什么东西可以帮助清理它)。但当我有非唯一行(例如,每个customer_id有五个不同的事务)时,它为我提供了一个扩展的解决方案

df.groupby('customer_id').agg({'amount':['sum'], 'reward_':['sum'], 'difficulty':['mean'], 
                                            'duration':['mean'], 'male':['mean'], 'male':['mean'], 
                                            'income':['mean'], 'days':['mean'], 'age':['mean'], 
                                            'customer_id':['count']}).reset_index()

df_grouped = starbucks_grouped.droplevel(1, axis = 1) 

我的输出是

您可以这样做,包括groupby中的所有其他列,然后在聚合后重置索引:

df.groupby(df.columns.difference(['amount']).tolist())['amount']\
  .agg(total_sum='sum',total='count').reset_index()

输出:

   age customer_id  days  difficulty  duration   income  male  reward  total_sum  total
0   45        id_1   608        10.0      10.0  62000.0     1     2.0      34.06      2

你可以做:

grouper = df.groupby('customer_id')
first_dict = {col: 'first' for col in df.columns.difference(['customer_id', 'amount'])}
o = grouper.agg({
     'amount': 'size', 
     **first_dict,
})
o['total'] = grouper.size().values

相关问题 更多 >