[英]How to count the number of group elements with pandas
I have a dataframe and just want count the number of elements in each group.我有一个 dataframe 并且只想计算每组中的元素数量。 I know, I can use the groupby().count() to get all the counts of all the columns, but it is too much for me, I just want the number of elements in each group.我知道,我可以使用 groupby().count() 来获取所有列的所有计数,但这对我来说太多了,我只想要每个组中的元素数。 How can I do this?我怎样才能做到这一点?
Here is the example:这是示例:
mydf = pd.DataFrame({"fruit":["apple","banana","apple"],"weight":[7,8,3],"price":[4,5,6]})
mydf
>> fruit price weight
>> 0 apple 4 7
>> 1 banana 5 8
>> 2 apple 6 3
If I use the groupby("fruit").mean(), I will get the value for each column.如果我使用 groupby("fruit").mean(),我将得到每一列的值。
mydf.groupby("fruit").mean()
>> price weight
>> fruit
>> apple 2 2
>> banana 1 1
But my expect output is:但我期望 output 是:
>> number_of_fruit
>> fruit
>> apple 2
>> banana 1
How can I do this?我怎样才能做到这一点?
You want size
to count the number of each fruit: 您想要size
来计算每个水果的数量:
In [102]:
mydf.groupby('fruit').size()
Out[102]:
fruit
apple 2
banana 1
dtype: int64
The answer by EdChum is great and I just want to give an alternative solution using value_counts function: EdChum 的答案很好,我只想使用 value_counts function 提供替代解决方案:
mydf["fruit"].value_counts()
Output: Output:
apple 2
banana 1
Name: fruit, dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.