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

如何基于Pandas DataFrame邮编前四位新增Gemeente市政名称列

解决代码与说明

问题2:提取postcode列前四位数字

荷兰邮政编码格式固定为4位数字+2位字母,直接对字符串列做切片即可:

# 提取全量数据的邮编前4位,存入新列postcode_prefix
df['postcode_prefix'] = df['postcode'].str[:4]

如果需要单独取某一行的前缀,比如第一行:

first_postcode_prefix = df['postcode'].iloc[0][:4]
# 输出为 '1774',和你给出的示例入参一致

问题1:批量查询新增Gemeente列

方案1:批量查询(效率更高,优先推荐)

如果nomi.query_postal_code支持传入整个前缀列表,直接批量查询后赋值即可:

import pandas as pd

# 原始数据集构造
data = {
    'globalId': {0: 4388064, 1: 4388200, 2: 4399344, 3: 4400638, 4: 4401765, 5: 4401831},
    'publicatieDatum': {0: '2018-07-31', 1: '2018-09-24', 2: '2018-08-02', 3: '2018-08-04', 4: '2018-08-05', 5: '2018-08-06'}, 
    'postcode': {0: '1774PG', 1: '7481LK', 2: '1068MS', 3: '5628EN', 4: '7731TV', 5: '5971CR'},
    'koopPrijs': {0: 139000.0, 1: 209000.0, 2: 267500.0, 3: 349000.0, 4: 495000.0, 5: 162500.0}
}
df = pd.DataFrame(data)

# 1. 提取邮编前缀
df['postcode_prefix'] = df['postcode'].str[:4]
# 2. 批量查询市政名称并赋值
df['Gemeente'] = nomi.query_postal_code(df['postcode_prefix'].tolist())

方案2:逐行查询(兼容只支持单个查询的接口)

如果接口一次只能查一个邮编前缀,用apply逐行处理即可,额外增加异常处理避免查询失败中断程序:

def get_gemeente(postcode):
    postcode_prefix = postcode[:4]
    try:
        # 如果接口返回的是包含市政名的单元素列表,改为 return nomi.query_postal_code([postcode_prefix])[0]
        return nomi.query_postal_code([postcode_prefix])
    except:
        # 查询失败返回空值,可根据需求调整返回内容
        return None

df['Gemeente'] = df['postcode'].apply(get_gemeente)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:24:03