【问题标题】:Pandas groupby and Multiindex熊猫 groupby 和 Multiindex
【发布时间】:2013-06-06 07:41:45
【问题描述】:

pandas 中是否有机会通过 MultiIndex 对数据进行分组? 我的意思是传递给 groupby 函数的不仅仅是键,还有键和值来预定义数据框列?

a = np.array(['foo', 'foo', 'foo', 'bar', 'bar', 'foo', 'foo'], dtype=object)
b = np.array(['one', 'one', 'two', 'one', 'two', 'two', 'two'], dtype=object)
c = np.array(['dull', 'shiny', 'dull', 'dull', 'dull', 'shiny', 'shiny'], dtype=object)
df = pd.DataFrame([a, b, c]).T
df.columns = ['a', 'b', 'c']
df.groupby(['a', 'b', 'c']).apply(len)

a    b    c    
bar  one  dull     1
     two  dull     1
foo  one  dull     1
          shiny    1
     two  dull     1
          shiny    2

但我真正想要的是以下内容:

mi = pd.MultiIndex(levels=[['foo', 'bar'], ['one', 'two'], ['dull', 'shiny']],
                   labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]])
#pseudocode
df.groupby(['a', 'b', 'c'], multi_index = mi).apply(len)
a    b    c    
bar  one  dull     1
          shiny    0
     two  dull     1
          shiny    0
foo  one  dull     1
          shiny    1
     two  dull     1
          shiny    2

我看到它的方式是在 groupby 对象上创建额外的包装器。或者这个功能很适合 pandas 的哲学,它可以包含在 pandas 库中?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只需重新索引和填充!

    In [14]: df.groupby(['a', 'b', 'c']).size().reindex(index=mi).fillna(0)
    Out[14]: 
    foo  one  dull     1
              shiny    1
         two  dull     1
              shiny    2
    bar  one  dull     1
              shiny    0
         two  dull     1
              shiny    0
    dtype: float64
    

    【讨论】:

    • 我认为可以包含的可能是关键字dropna=False(通常默认为True)以包含mi的所有组合(这就是你在这里所拥有的)......这是相似的我们在 0.11.1 中引入的新功能:pandas.pydata.org/pandas-docs/dev/groupby.html#filtration,它具有相同的属性...
    • 谢谢,太好了!我的第一个问题是关于交叉表功能的——所以你也回答了stackoverflow.com/questions/17003034/…
    • 在我的熊猫(版本 0.11.1-dev)中,过滤函数中没有 dropna=False 选项。正如我从源代码中了解到的那样,groupby 函数不会评估所有可能的组合。因此,我很想了解如何将此选项包含在 groupby 代码中。
    • 尝试更新到master,前几天才添加的
    • 您已经回答了我之前的问题,不是因为输入了“reindex”,而是发布问题告诉我,默认情况下,如果没有通过 reindex 解决方法,则在当前版本中不可能出现交叉表和 groupby 的这种行为。
    猜你喜欢
    • 2019-04-28
    • 2021-12-06
    • 2017-01-11
    • 2021-06-16
    • 2013-10-24
    • 2019-01-18
    • 2020-09-08
    • 2016-09-02
    • 2019-02-24
    相关资源
    最近更新 更多