6

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

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

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

4

3 回答 3

6

您可以使用字符串而不是函数,如下所示:

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
于 2019-04-09T18:46:44.060 回答
0

这可能有效:

df.groupby(['id', 'pushid']).agg({"sess_length": [ np.sum, np.mean, np.**size**]})
于 2020-10-28T18:50:58.487 回答
0

我想你的意思是:

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

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

于 2019-04-09T18:46:36.003 回答