在 Pandas 中聚合多列时如何重置索引

sou*_*rav 4 group-by aggregate-functions pandas

我有我试图分组的数据框,它看起来像这样

Cust_ID Store_ID month lst_buy_dt1  purchase_amt    
 1       20       10     2015-10-07  100
 1       20       10     2015-10-09  200
 1       20       10     2015-10-20  100
Run Code Online (Sandbox Code Playgroud)

我需要的最大的ls_buy_dt和最大或购买金额为每个cust_IDStore_ID在不同的数据帧每个月组合。示例输出:

Cust_ID Stored_ID month max_lst_buy_dt tot_purchase_amt
 1       20        10      2015-10-20     400
Run Code Online (Sandbox Code Playgroud)

我的代码在下面。

aggregations = {
    'lst_buy_dt1': { # Get the max purchase date across all purchases in a month
    'max_lst_buy_dt': 'max',       
    },
    'purchase_amt': {     # Sum the purchases 
    'tot_purchase': 'sum',   # Find the max, call the result "max_date"
    }
}

grouped_at_Cust=metro_sales.groupby(['cust_id','store_id','month']).agg(aggregations).reset_index()
Run Code Online (Sandbox Code Playgroud)

我能够获得正确的聚合。但是,数据框在列中包含一个我无法删除的附加索引。无法显示,但这是结果

list(grouped_at_Cust.columns.values)

[('cust_id', ''),
('store_id', ''),
('month', ''),
('lst_buy_dt1', 'max_lst_buy_dt'),
('purchase_amt', 'tot_purchase')]
Run Code Online (Sandbox Code Playgroud)

请注意最后 2 列中的层次结构。如何摆脱它?我只需要列max_lst_buy_dttot_purchase.

Ian*_*anS 6

编辑:根据您的评论,您可以简单地删除列索引的第一级。例如,使用更复杂的聚合:

aggregations = {
    'lst_buy_dt1': {
        'max_lst_buy_dt': 'max',       
        'min_lst_buy_dt': 'min',       
    },
    'purchase_amt': {
        'tot_purchase': 'sum',
    }
}
grouped_at_Cust = metro_sales.groupby(['cust_id', 'store_id', 'month']).agg(aggregations).reset_index()
grouped_at_Cust.columns = grouped_at_Cust.columns.droplevel(0)
Run Code Online (Sandbox Code Playgroud)

输出:

             tot_purchase min_lst_buy_dt max_lst_buy_dt
0   cust_id           100     2015-10-07     2015-10-07
1     month           100     2015-10-20     2015-10-20
2  store_id           200     2015-10-09     2015-10-09
Run Code Online (Sandbox Code Playgroud)

原答案

我觉得你的aggregations字典太复杂了。如果您遵循文档

agg = {
    'lst_buy_dt1': 'max',       
    'purchase_amt': 'sum',
}
metro_sales.groupby(['cust_id','store_id','month']).agg(agg).reset_index()
Out[19]: 
      index  purchase_amt lst_buy_dt1
0   cust_id           100  2015-10-07
1     month           100  2015-10-20
2  store_id           200  2015-10-09
Run Code Online (Sandbox Code Playgroud)

您现在需要的只是重命名结果的列:

grouped_at_Cust.rename(columns={
    'lst_buy_dt1': 'max_lst_buy_dt', 
    'purchase_amt': 'tot_purchase'
})
Run Code Online (Sandbox Code Playgroud)