【问题标题】:Pandas groupby agg - how to get counts?Pandas groupby agg - 如何获得计数?
【发布时间】: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

标签: python pandas group-by aggregate


【解决方案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 中所述?如果是这样,编辑您的答案以包含它会很有用。
      猜你喜欢
      • 2022-01-23
      • 2015-02-10
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多