熊猫groupby和Multiindex

大熊猫是否有机会通过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对象上创建其他包装。还是该功能与熊猫哲学相得益彰,可以包含在熊猫库中?


郎朗坤
浏览 168回答 1
1回答

皈依舞

只需重新索引和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    2bar  one  dull     1          shiny    0     two  dull     1          shiny    0dtype: float64
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python