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

为多城市GeoDataFrame计算面积:修复to_crs属性错误

解决GeoDataFrame逐行调用to_crs的AttributeError问题

错误原因

你遇到的AttributeError: 'Series' object has no attribute 'to_crs'是因为:遍历GeoDataFrame行时,每一行是Series对象,而to_crs是GeoPandas中GeoDataFrame/GeoSeries的专属方法,单个Series或Shapely几何对象(如Polygon)无法直接调用该方法。

修改方案

下面是针对多城市GeoDataFrame的适配代码,核心是将每行的几何对象包装为GeoSeries后再进行投影转换:

import geopandas as gpd

def calculate_cea_area(row, original_crs):
    # 将当前行的几何对象转为GeoSeries(必须指定原CRS)
    geom_series = gpd.GeoSeries(row.geometry, crs=original_crs)
    # 计算城市几何的中心坐标,用于构建CEA投影
    centroid = geom_series.centroid.iloc[0]
    lon, lat = centroid.x, centroid.y
    # 构建专属的圆柱等积(CEA)投影参数
    cea_crs = f"+proj=cea +lon_0={lon} +lat_ts={lat} +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs"
    # 转换到CEA投影并提取几何对象
    projected_geom = geom_series.to_crs(cea_crs).iloc[0]
    # 返回以平方米为单位的面积
    return projected_geom.area

# 假设你的多城市GeoDataFrame名为city_gdf,且已设置正确的原CRS(如EPSG:4326)
city_gdf['cea_area_sqm'] = city_gdf.apply(
    calculate_cea_area, 
    axis=1, 
    original_crs=city_gdf.crs
)

关键说明

  1. 包装GeoSeries:必须将单个几何对象转为GeoSeries并指定原CRS,这样GeoPandas才能识别并执行投影转换。
  2. 专属CEA投影:每个城市的CEA投影以自身几何中心为基准,确保面积计算的准确性。
  3. 参数传递:通过apply的额外参数传递原CRS,避免在函数内部硬编码,提升代码复用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:15:03