Python中如何按分组计算平均值并生成目标结果表格
方法1:仅使用Python标准库实现
无需安装额外第三方依赖,直接通过原生逻辑实现分组统计:
- 跳过表头遍历原数据,按国家维度累加分数、统计条目数
- 计算每个国家的平均分后,拼接表头生成最终结果
table = [['Country', 'Points'], ['Spain', '7'], ['Spain', '9'], ['Germany', '1'], ['Germany', '3']] # 存储每个国家的总分和出现次数 country_info = {} # 跳过表头遍历数据行 for row in table[1:]: country = row[0] point = int(row[1]) if country not in country_info: country_info[country] = {'sum': 0, 'cnt': 0} country_info[country]['sum'] += point country_info[country]['cnt'] += 1 # 组装结果 table_result = [table[0]] for country, info in country_info.items(): avg = str(int(info['sum'] / info['cnt'])) table_result.append([country, avg]) print(table_result)
运行后输出结果和你要求的完全一致:[['Country', 'Points'], ['Spain', '8'], ['Germany', '2']]
方法2:使用pandas实现
如果允许使用第三方数据分析库,代码逻辑会更简洁,适合数据量较大的场景:
import pandas as pd table = [['Country', 'Points'], ['Spain', '7'], ['Spain', '9'], ['Germany', '1'], ['Germany', '3']] # 转成DataFrame格式并修改Points列为数值类型 df = pd.DataFrame(table[1:], columns=table[0]) df['Points'] = df['Points'].astype(int) # 分组求平均值后转成嵌套列表格式 df_res = df.groupby('Country', as_index=False)['Points'].mean().astype(str) table_result = [table[0]] + df_res.values.tolist() print(table_result)
内容的提问来源于stack exchange,提问作者Jiakai Dong
相关产品推荐
相关产品推荐

