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

非Pandas实现:字典列表中按类别计算均值的方法

不用Pandas的分组均值计算方案

没问题,咱们完全可以用Python原生的字典和循环来实现这个按类别汇总均值的需求,不需要依赖Pandas。核心思路是先按urban_rural和technology的组合分组,统计每组的总速度和数据条数,最后计算均值并转换成你需要的字典列表格式。

具体实现代码

# 给定的查找表
lookup_table = [
    {"urban_rural": "urban", "technology": "FTTC", "speed": 50},
    {"urban_rural": "rural", "technology": "FTTC", "speed": 10},
    {"urban_rural": "urban", "technology": "FTTC", "speed": 30}
]

# 第一步:分组统计总速度和数据量
grouped_stats = {}
for item in lookup_table:
    # 用(urban_rural, technology)元组作为分组的唯一键
    group_key = (item["urban_rural"], item["technology"])
    if group_key not in grouped_stats:
        # 初始化分组的统计数据
        grouped_stats[group_key] = {"total_speed": 0, "count": 0}
    # 累加速度和计数
    grouped_stats[group_key]["total_speed"] += item["speed"]
    grouped_stats[group_key]["count"] += 1

# 第二步:计算均值并转换成目标格式
lookup_table_mean_values = []
for (urban_rural, tech), stats in grouped_stats.items():
    mean_speed = stats["total_speed"] / stats["count"]
    lookup_table_mean_values.append({
        "urban_rural": urban_rural,
        "technology": tech,
        "speed": mean_speed
    })

# 打印结果看看
print(lookup_table_mean_values)

代码说明

  1. 分组逻辑:用(urban_rural, technology)的元组作为字典的键,这样能确保每个不同的类别组合都被单独分组。
  2. 统计累加:遍历每个数据项时,对应分组的总速度和计数分别累加。
  3. 均值计算:遍历统计好的分组数据,用总速度除以计数得到均值,再包装成你需要的字典结构。

运行结果

对于你提供的示例数据,运行后会得到:

[
    {"urban_rural": "urban", "technology": "FTTC", "speed": 40.0},
    {"urban_rural": "rural", "technology": "FTTC", "speed": 10.0}
]

内容的提问来源于stack exchange,提问作者Thirst for Knowledge

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:00:39