我有我试图分组的数据框,它看起来像这样
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
我需要最大的
ls_buy_dt
和最大或每个购买金额cust_ID
, Store_ID
每个月在不同数据框中的组合。示例输出:Cust_ID Stored_ID month max_lst_buy_dt tot_purchase_amt
1 20 10 2015-10-20 400
我的代码在下面。
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()
我能够获得正确的聚合。但是,数据框在列中包含一个我无法删除的附加索引。无法显示,但这是结果
list(grouped_at_Cust.columns.values)
[('cust_id', ''),
('store_id', ''),
('month', ''),
('lst_buy_dt1', 'max_lst_buy_dt'),
('purchase_amt', 'tot_purchase')]
请注意最后 2 列中的层次结构。如何摆脱它?我只需要列
max_lst_buy_dt
和 tot_purchase
.
最佳答案
编辑 :根据您的评论,您可以简单地删除列索引的第一级。例如,使用更复杂的聚合:
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)
输出:
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
原答案
我想你的
aggregations
字典太复杂了。如果您关注 documentation :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
您现在需要的只是重命名结果的列:
grouped_at_Cust.rename(columns={
'lst_buy_dt1': 'max_lst_buy_dt',
'purchase_amt': 'tot_purchase'
})
关于pandas - 在 Pandas 中聚合多列时如何重置索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39568965/