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

使用Pandas计算候选人bush、gore的县域平均得票数

候选人县域平均得票数计算实现

需求说明

  • 基于Pandas处理选举数据集,计算bush、gore两位候选人在各县获得的平均得票数
  • 函数接收两个入参:数据集文件名filename、候选人得票对应的列名column,最终返回指定候选人的县域平均得票数

数据集字段说明

  • npop:县域总人口
  • wht:白人人口占比
  • blk:黑人人口占比
  • his:拉美裔人口占比
  • bush:候选人bush得票数
  • gore:候选人gore得票数

样例数据

npopwhtblkhisbushgore
19832674.421.54.73422447465
2076182.416.81.557102492
1462238012.41.23873718950

补全后完整代码

原有函数框架仅缺失列均值计算逻辑,直接调用Pandas Series的均值方法即可,补全后代码如下:

import pandas as pd

def averageCandidateVotes(filename, column):
   input_data = pd.read_csv(filename)
   candidate_votes = input_data[column]
   avg_vote = candidate_votes.mean()
   return avg_vote

使用方式

  • 计算bush的县域平均得票:调用averageCandidateVotes("数据集文件路径.csv", "bush")
  • 计算gore的县域平均得票:调用averageCandidateVotes("数据集文件路径.csv", "gore")

注:mean()方法会自动忽略列中的空值,计算所有有效县域得票的算术平均值,符合县域平均得票的计算要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:09:26