如何将Pandas groupby聚合结果的Asset_Type转为列?
将GroupBy结果的行类别转为宽表格式
你通过以下代码创建了分组聚合后的DataFrame:
Index = right_asset_df.groupby(['Year','Asset_Type']).agg({ 'Titre':'count', 'psqm':'median', 'Superficie':'median', 'Montant':'median' }).reset_index()
当前结果中Asset_Type(包含Appart和Villa两个类别)以行的形式展示,希望将每个类别转为单独的列,实现宽表格式输出。
方法1:使用pivot方法
直接对聚合后的DataFrame调用pivot,指定行索引、目标列字段以及需要转换的指标:
# 转换为宽表结构 wide_df = Index.pivot( index='Year', columns='Asset_Type', values=['Titre', 'psqm', 'Superficie', 'Montant'] ).reset_index() # 可选:整理多层列名为单层格式,更易读取 wide_df.columns = ['_'.join(col).strip() if col[1] else col[0] for col in wide_df.columns.values]
处理后会生成类似Titre_Appart、psqm_Villa的列名,每个Asset_Type的指标会单独成列。
方法2:GroupBy后直接用unstack
可以省略reset_index步骤,直接对GroupBy聚合结果调用unstack,将Asset_Type层级转为列:
# 聚合后直接转换结构 wide_df = right_asset_df.groupby(['Year','Asset_Type']).agg({ 'Titre':'count', 'psqm':'median', 'Superficie':'median', 'Montant':'median' }).unstack(level='Asset_Type').reset_index() # 可选:整理列名 wide_df.columns = ['_'.join(col).strip() if col[1] else col[0] for col in wide_df.columns.values]
内容的提问来源于stack exchange,提问作者bravopapa
相关产品推荐
相关产品推荐

