大熊猫是否有机会通过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
添加回答
举报
0/150
提交
取消