【问题标题】:Sum, max and mean the values in a different column for each unique value in a column with Python使用 Python 对一列中的每个唯一值求和、最大值和平均值
【发布时间】:2023-02-05 21:30:23
【问题描述】:

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

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]},
)

有了一个函数,对于“机器”列中的每个唯一值,我想自动打印这样的句子:

  • 对于机器总和是 39

    对于机器平均值是 6.5

    对于一台机器,最大值是 12

  • 对于 b 机器总和是 50

    对于 b 机器,平均值是 8.3

    对于 b 机器,最大值为 9

  • 对于 c 机器总和是 12

    对于 c 机器,平均值是 12

    对于 c 机器,最大值为 12

  • 对于 e 机器总和是 9

    对于电子机器,均值为 9

    对于 e machine max 是 9

我怎么能基本上写一个定义?

【问题讨论】:

    标签: python pandas function


    【解决方案1】:

    machine 分组并为每组总结meters

    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
    

    【讨论】:

    • 谢谢@RomanPerekhrest。这正是我的意思(:如果我想同时打印总计和平均值,我是否必须编写一个新函数(用“平均值”替换此函数的“总和”部分)或者我可以添加到此函数并解决它具有单一功能?
    • @volkan,用额外的预期输出更新你的主要问题
    • 我更新了扩展问题@RomanPerekhrest 的标题
    猜你喜欢
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    相关资源
    最近更新 更多