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

按DataFrame列设置GeoDataFrame标记颜色时遇JSON序列化错误

问题解决:根据GeoDataFrame列设置标记颜色报错

报错原因

你错误地将函数marker_color直接传给了folium.Icon的color参数,而color需要的是具体的颜色字符串(比如'red'、'blue'),并非函数。同时explore方法会把marker_kwds中的内容序列化为JSON,函数无法被序列化,因此抛出Object of type function is not JSON serializable错误。

正确代码写法

需要让marker_kwds里的icon对应一个接收feature对象并返回folium.Icon实例的函数,这样每个要素都会根据自身的Colors列值生成对应颜色的标记:

方式1:定义独立函数

import folium

def get_marker_icon(feature):
    # 根据要素的Colors列返回对应颜色的Icon
    return folium.Icon(color=feature['Colors'])

gdf1.explore(
    marker_type='marker',
    popup='Name',
    marker_kwds={'icon': get_marker_icon}
)

方式2:使用lambda简化

import folium

gdf1.explore(
    marker_type='marker',
    popup='Name',
    marker_kwds={'icon': lambda feat: folium.Icon(color=feat['Colors'])}
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:55:19