除了意思之外,如何统计pandas group by object中的行数? [英] How to count number of rows, in addition to mean, in pandas group by object?
问题描述
我有一个数据框 df
,我使用它的几列到 groupby
:
df ['col1','col2','col3','col4']。groupby(['col1','col2']) .mean()
以上述方式,我几乎可以得到我需要的表格(数据框架)。缺少的是一个包含每个组中行数的附加列。换句话说,我的意思是,但我也想知道有多少人被用来获得这些手段。例如,在第一组中有8个值,在第二组中有10个,依此类推。
c> groupby 对象, agg
函数可以列出一次应用几种聚合方法。这应该给你你需要的结果:
df [['col1','col2','col3','col4 ']]。groupby(['col1','col2'])。agg(['mean','count'])
I have a data frame df
and I use several columns from it to groupby
:
df['col1','col2','col3','col4'].groupby(['col1','col2']).mean()
In the above way I almost get the table (data frame) that I need. What is missing is an additional column that contains number of rows in each group. In other words, I have mean but I also would like to know how many number were used to get these means. For example in the first group there are 8 values and in the second one 10 and so on.
On groupby
object, the agg
function can take a list to apply several aggregation methods at once. This should give you the result you need:
df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])
这篇关于除了意思之外,如何统计pandas group by object中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!