Python Folium弹窗条件样式不生效及KeyError问题求助
Folium弹窗样式不生效及KeyError问题解决
一、弹窗样式未生效的原因
你写的条件判断语句里,虽然生成了带颜色样式的status字符串,但根本没把这个字符串用到popup变量里,popup还是拼接了原始的stat值,所以样式自然不会生效。
修正后的代码片段
df = pd.read_csv("or_geo.csv") fo = folium.FeatureGroup(name="OR", overlay=True) for i, row in df.iterrows(): lat = df.at[i, 'lat'] lng = df.at[i, 'lng'] sp = df.at[i, 'sp'] stat = df.at[i,'status'] # 根据status生成带样式的字符串并存储 if stat == "To be surveyed": styled_stat = '<strong style="text-transform:uppercase; color:red;">' + stat + '</strong>' elif stat == "Survey arranged": styled_stat = '<strong style="text-transform:uppercase; color:blue;">' + stat + '</strong>' else: styled_stat = '<strong style="text-transform:uppercase; color:green;">' + stat + '</strong>' # 将带样式的stat拼接到popup中 popup = df.at[i,'sp'] + '<br>' + str(df.at[i, 'street']) + '<br>' + str(df.at[i, 'post code']) + '<br>' + styled_stat fo.add_child(folium.Marker(location=[lat,lng], popup=popup, icon=folium.Icon(color='blue', icon='glyphicon-calendar'))) map.add_child(fo)
二、KeyError: 'To be surveyed'的原因
你修改后的代码里用了.format(row[stat], style),这里有两个明显问题:
row[stat]是用stat的具体值(比如"To be surveyed")作为键去取行数据,但row的键是CSV的列名(比如"status"),不是status列的内容值,所以会出现键不存在的报错。- 代码里从未定义过
style变量,就算键的问题解决了,也会因变量未定义报错。
正确写法
直接沿用上面修正后的逻辑,把生成好的styled_stat拼接到popup即可,不需要用错误的format写法。
内容的提问来源于stack exchange,提问作者Geographos
相关产品推荐
相关产品推荐

