You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将符合条件的分组均值结果生成指定格式字符串

实现指定格式的销售代表均值输出

需求说明

你已完成Pandas数据集的分组均值计算与筛选,需将筛选结果格式化为指定字符串:"The reps in the target metrics are: name1 with mean1, name2 with mean2, ..."

解决方案代码

完整实现代码

import pandas as pd

# 创建数据集
dataset = pd.DataFrame()
dataset['name'] = ['Alex', 'Alex', 'Alex','Alex','Alex',
                   'Marie', 'Marie', 'Marie','Marie','Marie',
                   'Luke', 'Luke', 'Luke','Luke','Luke']
dataset['sales'] = [690,451,478,524,750,452,784,523,451,125,854,745,856,900,105]

# 分组计算平均销售额
result_grouped = dataset.groupby(['name']).aggregate({'sales': 'mean'})
# 筛选平均销售额超过500的销售代表
filtered_reps = result_grouped[result_grouped['sales'] > 500]

# 生成每个代表的描述片段
rep_strings = [f"{name} with {mean_sales}" for name, mean_sales in filtered_reps.itertuples()]
# 拼接成目标格式的字符串
final_output = f"The reps in the target metrics are: {', '.join(rep_strings)}"

# 打印结果
print(final_output)

代码解释

  1. 筛选目标记录:通过result_grouped[result_grouped['sales'] > 500]获取平均销售额超500的销售代表数据
  2. 生成描述片段:用列表推导式结合itertuples()遍历筛选后的DataFrame,将每个代表的姓名和均值格式化为"姓名 with 均值"的字符串
  3. 拼接最终字符串:用', '.join(rep_strings)把所有描述片段用逗号连接,再与开头固定文本拼接成目标格式

运行输出

The reps in the target metrics are: Alex with 578.6, Luke with 692.0

内容的提问来源于stack exchange,提问作者R_Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:55:27