【问题标题】:Convert groupyby attributes into specific columns将 groupyby 属性转换为特定列
【发布时间】:2022-12-09 18:56:33
【问题描述】:

我有一个由 groupby 操作创建的数据框(请参见下面的代码和输出):

Index=right_asset_df.groupby(['Year','Asset_Type']).agg({'Titre':'count','psqm':'median','Superficie':'median', 'Montant':'median'}).reset_index()

输出是:

我不想将 Asset_Type 作为行,而是将其作为列,这意味着新输出 Index 应该为每个 Asset_Type(Appart 和 Villa)设置一列。

以下是输出示例:

如您所见,groupby 属性 Asset_Type 分别作为一个特定的列。

请问我怎样才能在 python 中做到这一点?谢谢

【问题讨论】:

  • 请将预期的输出添加到问题中。
  • 添加了输出。感谢您要求澄清

标签: python pandas dataframe group-by


【解决方案1】:

快速的方法是使用 Pivot:

# Pivot table with (index, columns, values)
df = Index.pivot(['Year'], 'Asset_Type',['Titre','psqm','Superficie','Montant']).reset_index()

# Instack multi level in columns
df.columns = ['_'.join(col) for col in df.columns]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    相关资源
    最近更新 更多