为了账号安全,请及时绑定邮箱和手机立即绑定

熊猫groupby和Multiindex

熊猫groupby和Multiindex

郎朗坤 2021-03-14 05:15:12
大熊猫是否有机会通过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]).Tdf.columns = ['a', 'b', 'c']df.groupby(['a', 'b', 'c']).apply(len)a    b    c    bar  one  dull     1     two  dull     1foo  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]])#pseudocodedf.groupby(['a', 'b', 'c'], multi_index = mi).apply(len)a    b    c    bar  one  dull     1          shiny    0     two  dull     1          shiny    0foo  one  dull     1          shiny    1     two  dull     1          shiny    2我看到的方式是在groupby对象上创建其他包装。还是该功能与熊猫哲学相得益彰,可以包含在熊猫库中?
查看完整描述

1 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

只需重新索引和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


查看完整回答
反对 回复 2021-03-31
  • 1 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号