在大熊猫聚合多个列时如何重置指标
问题描述:
我有我的,看起来像这样在大熊猫聚合多个列时如何重置指标
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
我需要为每个cust_ID
,Store_ID
最大的ls_buy_dt
和最大或购买金额试图组数据帧每个月在不同的数据框中进行组合。样品输出:
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'
})
感谢。我这样写字典是因为我可能需要多个聚合。例如, - 我将需要lst_buy_dt1的最大值和最小值。处理这个问题的最好方法是什么? – sourav
谢谢伊恩。但我的问题是如果我需要同一列的2个聚合(最小值和最大值)该怎么办?说在这种情况下,我需要最大和最小值为lst_buy_dt1。在这种情况下,我想,我将不得不恢复到我创建的字典。让我知道是否有更好的方法来做到这一点 – sourav
@sourav,这是我的观点,我的编辑与你的字典一起工作。我已经修改了我的问题,使其更清楚。 – IanS