简体   繁体   English

所有组组合的值计数

[英]Value counts for all combinations of groups

I have a dataframe with multiple group columns and a value column. 我有一个包含多个组列和一个值列的数据框。

   a  b  val
0  A  C  1
1  A  D  1
2  A  D  1
3  A  D  2
4  B  E  0

For any one group, for eg a==A , b==C I can do value_counts on the series slice. 对于任何一组,例如对于a==Ab==C我可以在序列切片上进行value_counts How can I get the value counts of all possible combinations of the group columns in a dataframe format similar to: 如何获取类似于数据框格式的组列的所有可能组合的值计数:

  a  b val counts
0 A  C 1   1
1 A  D 1   2
2 A  D 2   1
2 B  E 0   1

is that what you want? 那是你要的吗?

In [47]: df.groupby(['a','b','val']).size().reset_index()
Out[47]:
   a  b  val  0
0  A  C    1  1
1  A  D    1  2
2  A  D    2  1
3  B  E    0  1

or this? 或这个?

In [43]: df['counts'] = df.groupby(['a','b'])['val'].transform('size')

In [44]: df
Out[44]:
   a  b  val  counts
0  A  C    1       1
1  A  D    1       3
2  A  D    1       3
3  A  D    2       3
4  B  E    0       1

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

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