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

如何将位置列表映射至DataFrame以匹配邮政编码

如何将地理编码位置信息映射到DataFrame的对应邮政编码行

需求说明

我们有一个包含postal code列的DataFrame,以及从地理编码器提取的位置信息列表location = ['country', 'city', 'state', 'postal-code'],需要将每个邮政编码对应的国家、州、城市信息添加到DataFrame中,得到包含新列的目标结构。

解决方案

步骤1:构建邮政编码与位置信息的映射

首先将地理编码器返回的结果整理为邮政编码为键,位置信息为值的字典,方便后续匹配:

# 示例:地理编码器返回的结果结构
geo_results = [
    {'postal-code': '1111', 'country': 'Country1', 'state': 'State1', 'city': 'City1'},
    {'postal-code': '2222', 'country': 'Country2', 'state': 'State2', 'city': 'City2'},
    {'postal-code': '3333', 'country': 'Country3', 'state': 'State3', 'city': 'City3'},
    {'postal-code': '4444', 'country': 'Country4', 'state': 'State4', 'city': 'City4'},
    {'postal-code': '5555', 'country': 'Country5', 'state': 'State5', 'city': 'City5'},
]

# 生成邮政编码到位置信息的映射字典
postal_location_map = {
    item['postal-code']: {k: item[k] for k in ['country', 'state', 'city']} 
    for item in geo_results
}

步骤2:合并位置信息到原DataFrame

提供两种常用方法,可根据数据量选择:

方法一:使用apply逐行匹配(适合小数据量)
import pandas as pd

# 原DataFrame
original_df = pd.DataFrame({
    'ID': [1, 2, 3, 4, 5],
    'postal code': ['1111', '2222', '3333', '4444', '5555']
})

# 添加country、state、city列
original_df[['country', 'state', 'city']] = original_df['postal code'].apply(
    lambda code: pd.Series(postal_location_map.get(code, {'country': None, 'state': None, 'city': None}))
)
方法二:使用merge合并(适合大数据量,效率更高)

将地理结果转为DataFrame后,通过postal code列与原DataFrame合并:

# 将地理结果转为DataFrame并统一列名
geo_df = pd.DataFrame(geo_results).rename(columns={'postal-code': 'postal code'})

# 合并DataFrame
merged_df = original_df.merge(
    geo_df[['postal code', 'country', 'state', 'city']],
    on='postal code',
    how='left'  # 保留原DataFrame所有行,无匹配则填充NaN
)

最终结果

处理后的DataFrame结构如下:

ID postal code  country   state    city
0   1        1111  Country1  State1  City1
1   2        2222  Country2  State2  City2
2   3        3333  Country3  State3  City3
3   4        4444  Country4  State4  City4
4   5        5555  Country5  State5  City5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:45:38