Pandas groupby agg - 如何获得计数?

Posted

技术标签:

【中文标题】Pandas groupby agg - 如何获得计数?【英文标题】:Pandas groupby agg - how to get counts? 【发布时间】:2019-08-31 02:52:00 【问题描述】:

我正在尝试获取指标的总和、平均值和计数

df.groupby(['id', 'pushid']).agg("sess_length": [ np.sum, np.mean, np.count])

但我得到“模块'numpy'没有属性'count'”,我尝试了不同的方式来表达count函数但无法让它工作。如何将汇总记录数与其他指标一起计算?

【问题讨论】:

你只想要len吗?不确定您对表达计数函数的不同方式的含义 - numpy 当然没有 np.count,正如您所见。这个函数的作用是什么? 你可以使用np.size @jxc sizenan 计为一行,count 将排除nan 【参考方案1】:

您可以使用字符串代替函数,如下所示:

df = pd.DataFrame(
    "id": list("ccdef"), "pushid": list("aabbc"), 
     "sess_length": [10, 20, 30, 40, 50]
)

df.groupby(["id", "pushid"]).agg("sess_length": ["sum", "mean", "count"])

哪些输出:

           sess_length
                   sum mean count
 id pushid
 c  a               30   15     2
 d  b               30   30     1
 e  b               40   40     1
 f  c               50   50     1

【讨论】:

【参考方案2】:

我想你的意思是:

df.groupby(['id', 'pushid']).agg("sess_length": [ 'sum', 'count','mean'])

如documentation of pandas 中所述,您可以使用字符串参数,如“sum”、“count”。 TBH 这是进行这些聚合的更可取的方式。

【讨论】:

【参考方案3】:

这可能有效:

df.groupby(['id', 'pushid']).agg("sess_length": [ np.sum, np.mean, np.**size**])

【讨论】:

这种语法是否比使用 [ 'sum', 'mean', 'count'] 有好处,如去年的 the accepted answer 中所述?如果是这样,编辑您的答案以包含它会很有用。

以上是关于Pandas groupby agg - 如何获得计数?的主要内容,如果未能解决你的问题,请参考以下文章

Pandas groupby(),agg() - 如何在没有多索引的情况下返回结果?

python pandas, DF.groupby().agg(), agg() 中的列引用

python处理数据的风骚操作[pandas 之 groupby&agg]

Pandas GroupBy.agg() 抛出 TypeError: aggregate() 缺少 1 个必需的位置参数:'arg'

Pandas Groupby Agg 函数不减少

Pandas`agc`列表,“AttributeError / ValueError:函数不减少”