我有以下 df:
dfdict = {'letter': ['a', 'a', 'a', 'b', 'b'], 'category': ['foo', 'foo', 'bar', 'bar', 'spam']}
df1 = pd.DataFrame(dfdict)
category letter
0 foo a
1 foo a
2 bar a
3 bar b
4 spam b
我希望它像这样输出一个聚合计数 df:
a b
foo 2 0
bar 1 1
spam 0 1
这看起来应该是一个简单的操作。我已经弄清楚如何使用
df1 = df1.groupby(['category','letter']).size()
得到:
category letter
bar a 1
b 1
foo a 2
spam b 1
这更接近了,只是现在我需要顶部的字母 a、b
和向下的计数。
最佳答案
您可以使用crosstab
pd.crosstab(df1.category,df1.letter)
Out[554]:
letter a b
category
bar 1 1
foo 2 0
spam 0 1
要修复您的代码,请添加 unstack
df1.groupby(['category','letter']).size().unstack(fill_value=0)
Out[556]:
letter a b
category
bar 1 1
foo 2 0
spam 0 1
关于Python: Pandas 中的数据框操作和聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49868377/