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

如何利用GeoDataFrame将英国市县映射至行政区以合并数据集?

用GeoDataFrame匹配市县与行政区并合并数据集

1. 先梳理GeoDataFrame的关键字段

加载你的BFC GeoDataFrame,确认其中的市县名称与对应行政区名称字段——英国2021年BFC数据通常包含BFC21NM(市县/单一管理区名称)和LAD21NM(所属行政区名称),你可以根据实际输出调整字段名:

import geopandas as gpd
import pandas as pd

# 加载GeoDataFrame
bfc_gdf = gpd.read_file("你的BFC GeoJSON文件路径")

# 查看核心字段示例
print(bfc_gdf[["BFC21NM", "LAD21NM"]].head())

2. 标准化名称格式(避免匹配失败)

两个数据集的名称常存在大小写、前缀(如"City of")、空格差异,先统一格式:

# 处理GeoDataFrame的名称:转小写、去空格、移除冗余前缀
bfc_gdf["clean_bfc_name"] = bfc_gdf["BFC21NM"].str.lower().str.strip()
bfc_gdf["clean_bfc_name"] = bfc_gdf["clean_bfc_name"].str.replace(r"city of |borough of |district of ", "", regex=True)

# 用同样规则处理housing_df的市县名称
housing_df["clean_housing_name"] = housing_df["你的市县列名"].str.lower().str.strip()
housing_df["clean_housing_name"] = housing_df["clean_housing_name"].str.replace(r"city of |borough of |district of ", "", regex=True)

3. 构建市县→行政区的映射关系

从GeoDataFrame中提取唯一的市县-行政区对应关系,避免重复映射:

# 去重后生成映射字典
district_mapping = bfc_gdf.drop_duplicates(subset="clean_bfc_name")[["clean_bfc_name", "LAD21NM"]].set_index("clean_bfc_name")["LAD21NM"].to_dict()

4. 给housing_df匹配行政区字段

用映射字典为housing_df添加行政区列:

# 匹配行政区
housing_df["行政区名称"] = housing_df["clean_housing_name"].map(district_mapping)

# 检查匹配失败的行(可选)
unmatched = housing_df[housing_df["行政区名称"].isna()]
print("匹配失败的市县:", unmatched["clean_housing_name"].unique())

5. 处理匹配失败的情况(模糊匹配)

若存在名称拼写差异,用fuzzywuzzy做模糊匹配:

from fuzzywuzzy import process

def match_district(name):
    if pd.isna(name):
        return None
    # 匹配相似度≥80的名称(阈值可调整)
    match, score = process.extractOne(name, list(district_mapping.keys()))
    return district_mapping[match] if score >= 80 else None

# 为匹配失败的行重新匹配
housing_df.loc[housing_df["行政区名称"].isna(), "行政区名称"] = housing_df.loc[housing_df["行政区名称"].isna(), "clean_housing_name"].apply(match_district)

注:需先安装依赖:pip install fuzzywuzzy python-Levenshtein

6. 合并两个数据集

housing_df已添加行政区字段,直接与unemp_p_df按行政区名称合并:

# 假设unemp_p_df的行政区列名为"行政区名称",替换为你的实际列名
merged_df = pd.merge(housing_df, unemp_p_df, on="行政区名称", how="left")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:47:09