[英]Counting frequencies of the corresponding values in pandas [python 3]
I have the dataset with the following values: 我的数据集具有以下值:
var1 var2
1234 abc
2345 bcs
5678 csd
1234 abc
1234 bcs
5678 csd
1234 bcs
1234 xyz
1234 abc
9101 zzz
I need for every unique value in column var1 to count and show the top 3 frequency counts of the corresponding values in var2, and get the output, for example: 我需要对var1列中的每个唯一值进行计数,并显示var2中相应值的前3个频率计数,并获取输出,例如:
var1 var2 count
1234 abc 3
1234 bcs 2
1234 xyz 1
5678 csd 2
9101 zzz 1
What's the most efficient way of doing that? 最有效的方法是什么?
You need to include nlargest
您需要包括nlargest
df.groupby('var1').var2.apply(lambda x: x.value_counts().nlargest(3)) \
.reset_index(name='count').rename(columns={'level_1': 'var2'})
var1 var2 count
0 1234 abc 3
1 1234 bcs 2
2 1234 xyz 1
3 2345 bcs 1
4 5678 csd 2
5 9101 zzz 1
df_a.groupby(['var1','var2'])['var2'].agg({'count':'count'}).reset_index()
这工作:
df.groupby(['var1','var2']).count()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.