我有一个像这样的 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]},
)
通过一个函数,对于“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/