【问题标题】:Round while groupping by in pandas with agg function使用 agg 函数在 pandas 中分组时进行舍入
【发布时间】:2020-05-17 07:21:22
【问题描述】:

是否有可能将这个组中 C 的平均值四舍五入?

df.groupby('A').agg({'B':'sum', 'C':'mean'})

【问题讨论】:

  • df.groupby('A').agg({'B':'sum', 'C':lambda x: np.round(np.mean(x))})
  • 为什么不在单独的行中舍入结果?这将更具可读性,而不是在一行中堆积太多东西。

标签: python python-3.x pandas pandas-groupby


【解决方案1】:

您可以在聚合之后放置轮次,如下所示:

df.groupby('A').agg({'B':'sum', 'C':'mean'}).round(2)

在聚合中,不能在内部包含圆形。因此,您可以在聚合之后放置round。这是一种简单有效的方法。

Round(2) 会将其四舍五入到小数点后两位。您可以更改 2 以包含您想要将数字四舍五入的任何小数位数。例如,要四舍五入到小数点后 3 位,您可以使用 .round(3) 等等。

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2021-07-14
    相关资源
    最近更新 更多