简体   繁体   English

Pandas groupby和Multiindex

[英]Pandas groupby and Multiindex

Is there any opportunity in pandas to groupby data by MultiIndex? 在Pandas中有没有机会通过MultiIndex对数据进行分组? By this i mean passing to groupby function not only keys but keys and values to predefine dataframe columns? 通过这个我的意思是传递给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

But what I actually want is the following: 但我真正想要的是以下内容:

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

The way i see it is in creation of additional wrapper on groupby object. 我看到它的方式是在groupby对象上创建额外的包装器。 Or maybe this feature feets well to pandas philosophy and it can be included in the pandas lib? 或许这个功能很好地适应了熊猫哲学,它可以包含在熊猫lib中?

just reindex and fillna! 只是重新索引和fillna!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM