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

如何在Pandas DataFrame中提取经纬度并生成均值列?

解析GeoJSON并计算经纬度均值

可以实现你的需求,以下是具体步骤和代码:

1. 导入依赖库

import pandas as pd
import json

2. 构造示例数据(或直接使用你的现有DataFrame)

# 模拟你的原始数据
data = {
    'geo': [
        '{"type":"MultiPolygon", "coordinates":[[-114.539, 56.3398], [-115.849,55.696], [-115.5279, 49.4193 ]]}',
        '{"type":"MultiPolygon", "coordinates":[[-117.0715, 53.18939], [-123.375, 52.9461]]}'
    ]
}
df = pd.DataFrame(data)

3. 解析GeoJSON列

先将geo列的JSON字符串转为Python字典,再提取其中的coordinates数组:

# 解析JSON字符串为字典
df['geo_dict'] = df['geo'].apply(json.loads)
# 提取坐标列表
df['coordinates'] = df['geo_dict'].apply(lambda x: x['coordinates'])

4. 计算经纬度均值并新增列

遍历每个coordinates数组,分离经度(每个子数组的第一个元素)和纬度(第二个元素),分别计算均值:

# 计算经度均值
df['avg_longitude'] = df['coordinates'].apply(lambda coords: pd.Series([pair[0] for pair in coords]).mean())
# 计算纬度均值
df['avg_latitude'] = df['coordinates'].apply(lambda coords: pd.Series([pair[1] for pair in coords]).mean())

5. (可选)清理中间辅助列

如果不需要中间的geo_dict和coordinates列,可以删除:

df = df.drop(['geo_dict', 'coordinates'], axis=1)

最终结果

运行完上述代码后,你的DataFrame会新增avg_longitude和avg_latitude两列,分别对应每组坐标的经纬度均值。

处理异常情况(可选)

如果你的数据中存在空的coordinates数组,为避免计算报错,可以添加判断逻辑:

df['avg_longitude'] = df['coordinates'].apply(lambda coords: pd.Series([pair[0] for pair in coords]).mean() if coords else None)
df['avg_latitude'] = df['coordinates'].apply(lambda coords: pd.Series([pair[1] for pair in coords]).mean() if coords else None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:07:11