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

如何通过经纬度坐标借助CountryInfo获取子区域?格式匹配问题咨询

问题分析与解决方案

核心问题

  • 你传入subregion函数的是Point几何对象,但CountryInfo里的latlng是[纬度值, 经度值]的数值列表,类型和格式完全不匹配,直接用==肯定匹配不到。
  • 地震数据的经纬度是浮点数,和CountryInfo里的latlng(多为近似值)直接用相等判断会因为精度问题匹配失败。

修正步骤

1. 统一坐标格式

把Point对象转换成和CountryInfo的latlng一致的[纬度, 经度]格式,注意你创建Point时用的是(经度, 纬度),提取时要反过来。

2. 改用近似匹配

放弃精确相等判断,通过判断经纬度差值在极小范围内(比如0.5度)来匹配,避免浮点数精度干扰。

3. 优化性能

提前实例化CountryInfo对象,不要在循环里重复创建,提升运行效率。

修正后的代码

import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
import seaborn as sns
from countryinfo import CountryInfo

# 获取数据
df = pd.read_csv("earthquakes.csv")

# 创建坐标点(Point参数为(经度, 纬度))
df_geometry = [Point(xy) for xy in zip(df.longitude, df.latitude)]
gdf = gpd.GeoDataFrame(df, geometry=df_geometry)

# 设置seaborn默认主题
sns.set_theme()

# 提前初始化CountryInfo,避免重复实例化
country_info = CountryInfo()
all_countries = country_info.all()

# 定义获取子区域的函数
def get_subregion(point):
    # 从Point中提取[纬度, 经度],和CountryInfo的latlng格式对齐
    point_latlng = [point.y, point.x]
    for info in all_countries.values():
        if "latlng" in info:
            country_latlng = info["latlng"]
            # 近似匹配:经纬度差值都在0.5度以内(可根据需求调整精度)
            if abs(point_latlng[0] - country_latlng[0]) < 0.5 and abs(point_latlng[1] - country_latlng[1]) < 0.5:
                return info["subregion"]
    # 匹配不到时返回None
    return None

# 为GeoDataFrame添加子区域列
gdf["subregion"] = gdf["geometry"].apply(get_subregion)

# 绘制散点图(修正原代码x轴与注释不符的问题,若需latitude可自行改回)
sns.jointplot(data=gdf, x="longitude", y="mag", hue="subregion")

额外说明

  • 原代码中sns.jointplot的x轴写为latitude,但注释标注的是“longitude / magnitude”,已修正为x="longitude",可根据实际需求调整。
  • 近似匹配的精度阈值(0.5度)可根据数据情况微调,阈值越小匹配越严格。
  • 偏远地区的坐标可能无法匹配到对应子区域,会返回None,可后续通过填充默认值或过滤处理空值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 02:37:22