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

使用Folium GeoJson绘制Pandas DataFrame卫星过境数据报错如何解决

解决方案

报错核心原因

  • folium的GeoJson接口不支持直接传入普通pandas DataFrame,仅支持标准GeoJSON对象/字符串、GeoPandas GeoDataFrame作为合法输入
  • 样式函数的入参是GeoJSON的feature结构,业务字段都存储在feature['properties']子节点下,原代码直接取x['countSp']无法正确读取数值

方案1:使用GeoPandas(推荐,代码最简)

先安装geopandas依赖,再将普通DataFrame转为GeoDataFrame即可直接传入:

import geopandas as gpd

# 转为GeoDataFrame,指定坐标系为WGS84(标准经纬度坐标系)
gdf = gpd.GeoDataFrame(df, geometry='geometry', crs="EPSG:4326")

# 修正样式函数,从properties中取countSp字段
style_func = lambda feature: {
        'fillColor': colormap_dept(feature['properties']['countSp']),
        'color': 'none',
        'weight': 0,
        'fillOpacity': 0.6 # 可按需调整,0为全透明,1为完全不透明
    }

folium.GeoJson(
    gdf,
    style_function=style_func,
).add_to(hmap)

# 可以直接把色阶添加到地图上当图例
colormap_dept.add_to(hmap)

方案2:无需额外安装依赖,手动构造GeoJSON结构

如果不想安装GeoPandas,可以手动把DataFrame转换为符合规范的GeoJSON字典:

from shapely.geometry import mapping

# 构造标准GeoJSON结构
geo_json_data = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": mapping(row['geometry']),
            "properties": {"countSp": row['countSp']}
        } for _, row in df.iterrows()
    ]
}

# 样式函数和方案1一致
style_func = lambda feature: {
        'fillColor': colormap_dept(feature['properties']['countSp']),
        'color': 'none',
        'weight': 0,
        'fillOpacity': 0.6
    }

folium.GeoJson(
    geo_json_data,
    style_function=style_func,
).add_to(hmap)

调整fillOpacity参数到0.4-0.8区间即可兼顾底图可见性和数据辨识度,完全满足半透明效果需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:45:02