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

标签 pandas group-by aggregate-functions

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

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_dttot_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/

相关文章:

python - Groupby 同一列中的多个项目

sql - 为什么 SQL Server 2008 在使用 GROUP BY 并且没有指定顺序时排序?

python - Pandas - 拆分一行值并与多行合并

apache-spark - Pyspark:在数据帧的不同组上应用 kmeans

mysql - SQL使用不同条件多次选择列

sql - 为两个字段创建两个数组,保持数组的排序顺序同步(没有子查询)

python dataframe 做类似 oracle connect_by 的事情吗?

python - 从 Python 到 Excel 的 Excel 公式格式

python - 按列值将 CSV 文件分类为不同的 CSV

python - 如何对 Pandas 中的特定列进行分组 + 对此应用统计数据?