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

如何基于列字符串子串合并两个DataFrame并填充列值?

解决方法

你原来的merge代码错误在于匹配键的设置逻辑混乱,同时直接传入Series作为匹配键的写法不符合Pandas的参数要求。以下是几种正确的实现方式:

方法1:使用merge并保留原始数据结构

这种方法会保留data的所有行,匹配不到的行urbanisation会保持空值:

import pandas as pd

# 执行merge,基于ZIP前4位匹配
merged_data = pd.merge(
    data,
    reference,
    left_on=data["ZIP code"].str[:4],  # 用data中ZIP的前4位作为左匹配键
    right_on="ZIP code category",       # 用reference中的类别列作为右匹配键
    how="left"                          # 左连接,保留data的所有行
)

# 将匹配到的城市化值赋值给原列,清理多余列
merged_data["urbanisation"] = merged_data["urbanisation_y"]
final_data = merged_data.drop(columns=["ZIP code category", "urbanisation_y"])

方法2:用assign创建临时匹配列(简洁链式写法)

final_data = (
    data.assign(zip_prefix=data["ZIP code"].str[:4])  # 临时生成ZIP前4位列
    .merge(reference, left_on="zip_prefix", right_on="ZIP code category", how="left")
    .assign(urbanisation=lambda df: df["urbanisation_y"])  # 替换原空值列
    .drop(columns=["zip_prefix", "ZIP code category", "urbanisation_y"])  # 清理临时列
)

方法3:使用map(高效字典映射)

如果只需要填充匹配值,这种方法更简洁高效:

# 先把reference转换成ZIP类别到城市化值的字典
urban_map = reference.set_index("ZIP code category")["urbanisation"].to_dict()

# 直接用ZIP前4位映射填充空值
data["urbanisation"] = data["ZIP code"].str[:4].map(urban_map)

以上方法都不会修改原始的ZIP code列,完全满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:39:34