Python 聚合行并创建列作为值计数

Python 聚合行并创建列作为值计数,python,pandas,Python,Pandas,我有一个数据框,看起来像: tt oo 0 g gh 1 g jj 2 g gh 3 t gh 4 t gh 我想以一个新的数据帧结束,该数据帧聚合在“tt”上,给出“oo”列的计数,这样看起来像: gh jj g 2 1 t 2 0 我尝试了一个透视表,但结果是“索引包含重复条目错误”。 t您可以使用groupby在一行中完成此操作: df.groupby('tt')['oo'].value_counts() Out[8]: tt

我有一个数据框,看起来像:

   tt  oo
0  g  gh
1  g  jj
2  g  gh
3  t  gh
4  t  gh
我想以一个新的数据帧结束,该数据帧聚合在“tt”上,给出“oo”列的计数,这样看起来像:

   gh  jj
g  2   1
t  2   0
我尝试了一个透视表,但结果是“索引包含重复条目错误”。
t

您可以使用
groupby
在一行中完成此操作:

df.groupby('tt')['oo'].value_counts()
Out[8]: 
tt    
g   gh    2
    jj    1
t   gh    2
dtype: int64
dfrm1 = pandas.DataFrame({'tt':['g', 'g', 'g', 't', 't'], 
                          'oo':['gh', 'jj', 'gh', 'gh', 'gh']})

dfrm1.groupby('tt')['oo'].value_counts().unstack(level=1).fillna(0.0)