【问题标题】:Pandas re-indexing with Multiindex on Index AND ColumnsPandas 在索引和列上使用 Multiindex 重新索引
【发布时间】:2018-10-24 12:34:17
【问题描述】:

我有一个长数据框,这些列采用这种格式:

id  gender  size    region_a_count  region_b_count  item_group
 x   m       x            x                x         x
 x   f       x            x                x         x
 x   f       x            x                x         x
 x   m       x            x                x         x
 x   f       x            x                x         x
 x   m       x            x                x         x   

性别、大小、item_group 和区域的每个组合都是独一无二的。所以不需要进行聚合。

我想将索引和列重新索引到这种类型的输出,单元格值保持不变

                    region_a         region_b        region_c   
                    m        f       m        f      m         f
      (index of size)
item_group  1                       
            2                       
            3                       
item_group  1                       
            2                       
            3                       

也就是说,具有索引以及具有多索引的列。我可以通过调用来执行索引部分:

df.groupby(["item_group","size"])

但列问题依然存在。

如何从现有数据框创建列多索引?

【问题讨论】:

  • 是否可以为x 设置一些值?
  • 嗨@jezrael,很难将它们粘贴格式良好。它们是数字和字符串的混合体。考虑到每种组合都是独一无二的,它们并不相关:)
  • 那么解决方案对您有用吗?如果没有,请随意将x 更改为abc123,并将其添加到预期输出中。
  • @jezrael 抱歉,没有看到您是回答问题的同一个人。是的,解决方案奏效了!谢谢:)

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

我相信你需要set_indexunstack

df1 = df.set_index(["item_group","size", "id","gender"]).unstack()

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 2020-04-12
    • 2017-03-02
    • 2023-03-10
    • 2018-12-29
    • 1970-01-01
    • 2019-11-19
    • 2014-01-12
    • 2021-01-31
    相关资源
    最近更新 更多