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

如何通过字典映射无循环聚合DataFrame生成多区域归属透视表

解决多区域重叠国家的DataFrame聚合透视问题

因为单个国家可能属于多个区域(比如US同时在region_1和region_2),直接用map会丢失其中一个关联,导致聚合结果错误。下面是无需循环的高效实现方案:

步骤1:重构区域-国家映射为多对多格式

先把原字典中的字符串格式国家列表拆分成单独行,生成每个国家对应的所有区域:

import pandas as pd

# 原数据
df = pd.DataFrame(
    {
        "country": ['US', 'US', 'CA', 'CA', 'JP', 'JP'],
        "sector": ['automotive', 'aviation', 'automotive', 'aviation', 'automotive', 'aviation'],
        "production": [100, 50, 30, 15, 95, 25]
    }
)
dict_country_per_region = {'region_1': 'US, CA', 'region_2': 'US, JP'}

# 转换映射字典为DataFrame并拆分国家列表
region_mapping = pd.DataFrame.from_dict(dict_country_per_region, orient='index', columns=['countries'])
region_mapping['countries'] = region_mapping['countries'].str.split(', ')
# 展开列表为多行,得到国家-区域的多对多映射表
region_mapping = region_mapping.explode('countries').reset_index().rename(columns={'index': 'region', 'countries': 'country'})

步骤2:合并原数据与映射表

通过merge关联原数据和映射表,确保每个国家对应的所有区域都被保留:

merged_df = df.merge(region_mapping, on='country', how='left')

步骤3:分组聚合生成目标透视表

按sector和region分组求和,再用unstack把区域转成列,得到最终格式:

result = merged_df.groupby(['sector', 'region'])['production'].sum().unstack()
print(result)

输出结果

region_1  region_2
sector                         
automotive        130       195
aviation           65        75

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:20:21