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

使用geopandas绘图报错'DataFrame' object has no attribute 'crs'

报错原因
  • 直接诱因是GeoDataFrame初始化时传参顺序错误。geopandas的GeoDataFrame构造函数参数顺序为GeoDataFrame(data=None, crs=None, geometry=None, ...),第二个位置参数是坐标系参数crs,不是几何列参数geometry。你写的gdf = GeoDataFrame(complete_major_accidents, geometry)把生成的点几何对象错误传给了crs参数,没有给geometry形参赋值,最终生成的是没有空间属性的普通pandas DataFrame,不存在GeoDataFrame专属的crs属性,绘图逻辑读取坐标系时直接触发属性错误。
  • 代码还存在两处隐性问题:一是生成点几何时用的是complete_nonmajor_accidents的经纬度字段,传入的属性表却是complete_major_accidents,数据源不匹配会导致点位和属性对应错误;二是没有为点数据显式指定坐标系,即使修复传参问题,也可能出现点位和底图坐标错位的情况。
修复方案

调整GeoDataFrame初始化逻辑:显式用关键字指定几何列,统一属性表和几何列的数据源,同时设置和底图匹配的坐标系(naturalearth_lowres默认使用WGS84地理坐标系,对应EPSG编码为4326)。
修复后的可运行代码片段如下:

import geopandas as gpd
from geopandas import GeoDataFrame

# 统一数据源:如果要绘制重大事故点位,就用complete_major_accidents的经纬度生成几何列
geometry = gpd.points_from_xy(complete_major_accidents.longitude, complete_major_accidents.latitude)
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# 修复传参:显式指定geometry参数,同步设置坐标系
gdf = GeoDataFrame(complete_major_accidents, geometry=geometry, crs="EPSG:4326")

ax = world[world['name'] == 'United Kingdom'].plot(figsize=(15, 15))
gdf.plot(ax=ax, marker='o', color='red', markersize=15, edgecolor='black')

如果实际要绘制的是非重大事故点位,把生成几何列和传入GeoDataFrame的数据源统一替换为complete_nonmajor_accidents即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:57:22