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

Streamlit嵌入Folium Choropleth地图时所有国家值显示为null问题

解决Folium Choropleth在Streamlit中显示所有国家数值为Null的问题

核心问题原因

你当前的代码没有使用筛选后的数据集生成Choropleth地图,而是直接传入了原始全量的food_ind_data。这导致地图无法匹配你通过选择框筛选出的指标和年份对应的数据,最终所有国家数值都显示为null。

修正后的代码

import streamlit as st
import folium
import pandas as pd
from streamlit_folium import st_folium

st.set_page_config(layout='wide')
geojson = 'World.geojson'
food_ind_data = pd.read_csv('Food_Security_Ind_Modified.csv')

m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodbpositron")

# 选择指标和年份
indicator = st.selectbox('Select an indicator:', food_ind_data.Item.unique())
filtered_year_options = food_ind_data.loc[food_ind_data.Item == indicator]['Year'].unique()
year = st.selectbox('Select a year or year span:', filtered_year_options)

# 关键步骤:根据选择的指标和年份筛选数据集
filtered_data = food_ind_data[(food_ind_data.Item == indicator) & (food_ind_data.Year == year)]

# 使用筛选后的数据集生成Choropleth
folium.Choropleth(
    geo_data=geojson,
    name='Food Security Indicators by Country',
    data=filtered_data,  # 替换为筛选后的数据集
    columns=('Area', 'Value'),
    key_on='feature.properties.name',
    fill_color="RdYlGn_r",
    fill_opacity=0.7,
    line_opacity=0.3,
    nan_fill_color='white',
    legend_name=f'{indicator} ({year})'
).add_to(m)

# 可选:添加弹窗显示国家详情(包含数值)
folium.features.GeoJson(
    geojson,
    name='Country Details',
    popup=folium.features.GeoJsonPopup(
        fields=['name'],
        aliases=['Country:'],
        localize=True,
        style_function=lambda x: {'fillColor': 'transparent', 'color': 'transparent'},
        tooltip=folium.features.GeoJsonTooltip(
            fields=['name'],
            aliases=['Country:'],
            localize=True
        )
    )
).add_to(m)

folium.LayerControl().add_to(m)

st_map = st_folium(m, width=1000)

额外排查建议

  • 验证筛选结果:可以添加st.dataframe(filtered_data)到代码中,确认筛选后的数据集包含有效Area和Value数据。
  • 检查名称匹配:即使你确认过关联键,仍需注意GeoJSON中的国家名称与CSV的Area字段是否完全一致(比如大小写、空格、简称/全称差异,如"U.S.A." vs "United States"),必要时统一两边的名称格式。
  • 清理缺失值:用filtered_data = filtered_data.dropna(subset=['Value'])去掉Value为空的行,避免无效数据影响地图渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:13:12