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

如何在Python中按国家汇总Pandas DataFrame的Allocation数值

按国家汇总Pandas DataFrame的Allocation列

这事儿用Pandas的groupby()配合sum()就能轻松搞定,我给你整理了完整的实现代码和说明:

完整代码示例

import pandas as pd

# 你的原始数据
ticker = ['YAR.OL', 'DNB.OL', 'TSLA', 'NHY.OL', 'SBO.OL', 'STB.OL']
country = ['Norway', 'Norway', 'United States', 'Norway', 'Norway', 'Norway']
alloc = [11.822, 2.917, 0.355, 74.158, 9.673, 1.075]

# 构建DataFrame(这里简化了Allocation列的赋值方式)
dfn = pd.DataFrame(country, columns=['country'])
dfn['Allocation'] = alloc

# 核心:按国家分组并对Allocation列求和
country_allocation_totals = dfn.groupby('country')['Allocation'].sum()

# 查看结果
print(country_allocation_totals)

运行结果

运行后会输出一个Series,清晰展示每个国家的总分配额:

country
Norway            99.645
United States      0.355
Name: Allocation, dtype: float64

额外:转成字典格式

如果需要更像你示例里的键值对格式,可以用to_dict()方法转换:

totals_dict = country_allocation_totals.to_dict()
print(totals_dict)
# 输出: {'Norway': 99.645, 'United States': 0.355}

简单说明

  • groupby('country'):把DataFrame按country列的唯一值分成不同的组
  • ['Allocation'].sum():对每个分组里的Allocation列计算总和,自动聚焦目标列完成汇总

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:57:28