在Pandas中有没有机会通过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对象上创建额外的包装器.或许这个功能很好地适应了熊猫哲学,它可以包含在熊猫lib中?
解决方法:
只是重新索引和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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。