pandas groupby和Multiindex [英] Pandas groupby and Multiindex

查看:106
本文介绍了 pandas groupby和Multiindex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any opportunity in pandas to groupby data by MultiIndex? By this i mean passing to groupby function not only keys but keys and values to predefine dataframe columns?

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

我看到的方式是在groupby对象上创建其他包装.还是该功能与熊猫哲学相得益彰,可以包含在熊猫库中?

The way i see it is in creation of additional wrapper on groupby object. Or maybe this feature feets well to pandas philosophy and it can be included in the pandas lib?

推荐答案

只需重新索引并填充内容!

just reindex and 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

这篇关于 pandas groupby和Multiindex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆