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

如何在Pandas中匹配两表County字段添加FIPS代码新列?

解决方案

问题分析

你原来的代码存在几个关键问题:

  • 列名错误:data[fips] 里的fips是DataFrame对象,不能作为新列名,需要指定字符串列名(比如'FIPS')
  • np.where用法错误:它需要三个参数(判断条件、满足条件时的值、不满足条件时的值),且直接用data.County == fips.CountyName会因为两个DataFrame行数不匹配,无法实现跨表的精准匹配
  • 变量引用错误:fipsCountyFIPS没有指定所属的DataFrame,应该写成fips['fipsCountyFIPS']

方法1:使用merge合并数据(推荐)

这种方法逻辑直观,能确保匹配准确,还能灵活处理不匹配的行:

import pandas as pd

# 读取原始数据
data = pd.read_csv("maindata.csv")
fips = pd.read_csv("fips2county.tsv", sep='\t')

# 合并数据,按County和CountyName匹配,新增FIPS列
merged_data = pd.merge(
    data,
    fips[['CountyName', 'fipsCountyFIPS']],  # 只保留需要的匹配列和目标列
    left_on='County',
    right_on='CountyName',
    how='left'  # 保留data的所有行,不匹配的FIPS列自动设为NaN
)

# 重命名列并清理冗余列(可选)
merged_data.rename(columns={'fipsCountyFIPS': 'FIPS'}, inplace=True)
merged_data.drop(columns=['CountyName'], inplace=True)

# 查看结果
print(merged_data.head())

方法2:使用map快速映射

如果只需要新增FIPS列,不需要合并其他数据,用map更简洁高效:

import pandas as pd

data = pd.read_csv("maindata.csv")
fips = pd.read_csv("fips2county.tsv", sep='\t')

# 创建CountyName到fipsCountyFIPS的映射字典
fips_map = fips.set_index('CountyName')['fipsCountyFIPS'].to_dict()

# 新增FIPS列,匹配不到的行设为NaN
data['FIPS'] = data['County'].map(fips_map)

# 查看结果
print(data.head())

额外处理建议

  • 如果匹配时存在大小写、空格差异(比如"Los Angeles County"和"los angeles county"),可以先统一格式:
    # 统一转为小写并去除首尾空格
    data['County'] = data['County'].str.strip().str.lower()
    fips['CountyName'] = fips['CountyName'].str.strip().str.lower()
    
  • 确保FIPS代码是5位格式(避免数字类型丢失前导零):
    fips['fipsCountyFIPS'] = fips['fipsCountyFIPS'].astype(str).str.zfill(5)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:41:05