如何基于Pandas DataFrame的postcode列提取前4位新增Gemeente字段
提取postcode列前4位数字实现代码
你的postcode列值统一为「4位数字+2位字母」的字符串格式,直接通过pandas字符串切片即可提取:
df['postcode_first4'] = df['postcode'].str[:4]
执行后postcode_first4列存储的就是所有postcode对应的前4位数字。
新增Gemeente列实现代码
根据nomi.query_postal_code的调用规则,分为两种实现场景:
- 若接口支持批量传入邮编列表查询,推荐使用批量调用方式,数据量大时效率更高:
# 提取所有前4位邮编 postcode4_list = df['postcode'].str[:4].tolist() # 批量查询Gemeente值 gemeente_res = nomi.query_postal_code(postcode4_list) # 赋值为新列 df['Gemeente'] = gemeente_res
- 若接口仅支持单次查询单个邮编,使用apply逐行调用:
df['Gemeente'] = df['postcode'].str[:4].apply(lambda x: nomi.query_postal_code([x])[0])
内容的提问来源于stack exchange,提问作者user17403003
相关产品推荐
相关产品推荐

