python - 使用 Python 对列中每个唯一值求和、最大值和平均值

标签 python pandas function

我有一个像这样的 pandas 数据框:

df = pd.DataFrame({'date': [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 7, 7],
                   'machine': ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'c', 'a', 'b', 'e', 'a', 'b'],
                   'meters': [12, 9, 7, 9, 4, 9, 3, 7, 12, 9, 7, 9, 4, 9]},
)

enter image description here

通过一个函数,对于“machine”列中的每个唯一值,我想自动打印如下句子:

  • 一台机器的总和是 39

    对于机器来说平均值是 6.5

    一台机器的最大值为 12

  • 对于b机器来说总和是50

    b 机器的平均值是 8.3

    b 机器的最大值为 9

  • 对于c机器来说总和是12

    对于c机器来说平均值是12

    对于 c 机器最大为 12

  • 对于 e 台机器来说,总和是 9

    对于 e 机器来说,平均值是 9

    对于 e 机器来说,最大值为 9

我怎样才能写出一个基本的定义?

最佳答案

机器分组并汇总每组的:

for m, s in df.groupby('machine')['meters'].sum().items():
    print(f'For {m} machine sum is {s}')

For a machine sum is 39
For b machine sum is 50
For c machine sum is 12
For e machine sum is 9

UPD:(由于扩展要求)

要进行更扩展的聚合,请使用以下方法(使用应用的 .agg 函数):

for m, d in df.groupby('machine')['meters'].agg(['sum', 'mean', 'max']).to_dict('index').items():
    print(f'For {m} machine: sum is {d["sum"]}, '
          f'mean is {d["mean"]}, max is {d["max"]}')

For a machine: sum is 39, mean is 6.5, max is 12
For b machine: sum is 50, mean is 8.333333333333334, max is 9
For c machine: sum is 12, mean is 12.0, max is 12
For e machine: sum is 9, mean is 9.0, max is 9

关于python - 使用 Python 对列中每个唯一值求和、最大值和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75352226/

相关文章:

python - 字典每个键分为多行

python - 使用 Pandas 按列值过滤

python - 根据索引的条件创建新列

python - Pandas : Usecols do not match columns, 列预期但未找到

c++ - 如何创建一个可以向其传递函数或仿函数的方法?

Javascript:在给定对象问题中动态创建函数

python - 按位置而不是字符拆分字符串

python - Python 中的 Perl 正则表达式

python - 我需要什么过滤器?只想保留高频值

javascript - JavaScript 装饰器的意义何在?