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

如何在Pandas长格式数据框中添加民主党候选人得票率列

计算选区民主党得票率并填充全选区数据行

需求说明

需要计算指定选举年份、指定选区中民主党候选人的总得票率,并将该得票率值填充到对应选区选举的所有候选人数据行中。现有Pandas数据框包含以下字段:

  • year:选举年份
  • state:州
  • district:选区
  • candidate:候选人姓名
  • party:所属党派
  • candidatevotes:候选人得票数
  • totalvotes:选区总票数

示例输入数据

year    state  district                   candidate       party  candidatevotes  totalvotes
0  1976  alabama         1              BILL DAVENPORT    DEMOCRAT           58906      157170 
1  1976  alabama         1                JACK EDWARDS  REPUBLICAN           98257      157170 
2  1976  alabama         1                     WRITEIN         NaN               7      157170
3  1976  alabama         2             J CAROLE KEAHEY    DEMOCRAT           66288      156362
4  1976  alabama         2  WILLIAM L "BILL" DICKINSON  REPUBLICAN           90069      156362

期望输出结果

year    state  district                   candidate       party  candidatevotes  totalvotes    Dem_vote_share
0  1976  alabama         1              BILL DAVENPORT    DEMOCRAT           58906      157170    0.374
1  1976  alabama         1                JACK EDWARDS  REPUBLICAN           98257      157170    0.374
2  1976  alabama         1                     WRITEIN         NaN               7      157170    0.374
3  1976  alabama         2             J CAROLE KEAHEY    DEMOCRAT           66288      156362    0.424
4  1976  alabama         2  WILLIAM L "BILL" DICKINSON  REPUBLICAN           90069      156362    0.424

解决方案代码

# 生成唯一选区标识列,将州和选区拼接
df['Unique_District'] = df[['state', 'district']].apply(lambda x: '-'.join(x.astype(str)), axis=1)

# 计算每个年份-选区的民主党总得票率
mapping_vals = (
    df[df['party'].eq('DEMOCRAT')]  # 筛选民主党候选人数据
    .set_index(['year', 'Unique_District'])  # 设置年份和唯一选区为索引
    .apply(lambda x: x['candidatevotes']/x['totalvotes'], axis=1)  # 计算单个民主党候选人得票率
    .groupby(level=[0,1]).sum()  # 按年份和唯一选区分组求和,得到该选区民主党总得票率
)

# 将得票率映射回原数据框的所有行
df['Dem_vote_share'] = df.set_index(['year', 'Unique_District']).index.map(mapping_vals)

内容的提问来源于stack exchange,提问作者Damon C. Roberts

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:30:49