简体   繁体   English

Group by 和 value_counts - 将结果作为列返回

[英]Group by and value_counts - return results as columns

I have a DF of the following:我有以下 DF:

    value     name     
      A      Steven     
      A      Steven    
      A      Ron    
      B      Joe     
      B      Steven     
      B      Ana       

I want to perform a value_counts() operation on the name column so the output will be a DF where the columns are the counters of the values :我想对 name 列执行 value_counts() 操作,因此输出将是一个 DF,其中列是值的计数器:

     value  Steven Ron  Joe Ana   
      A       2     1    0   0
      B       1     0    1   1            
      

Tried a group by+value_counts and than transposing the results but didn't reached the output.尝试了一组 by+value_counts,然后转置结果,但没有达到输出。

It is crosstab它是crosstab

pd.crosstab(df.value, df.name).reset_index().rename_axis(None,1)

Out[62]:
  value  Ana  Joe  Ron  Steven
0     A    0    0    1       2
1     B    1    1    0       1

You can do this with groupby and value_counts like this:你可以像这样使用groupbyvalue_counts来做到这一点:

df.groupby('value')['name'].value_counts().unstack(fill_value=0).reset_index()

Output:输出:

name value  Ana  Joe  Ron  Steven
0        A    0    0    1       2
1        B    1    1    0       1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM