在 streamlit 选择框中将国家与大陆匹配

Match countries with continents in streamlit selectbox

我有一个 df,我在其中使用 pycountry 获取国家/地区列和大洲列的全名,并像这样在 streamlit 中制作 select 框,

country              continent
Hong Kong              Asia
Montenegro            Europe
Rwanda                Africa
United States      North America
Germany               Europe
Myanmar                Asia
Saudi Arabia           Asia
etc..                  etc..

Streamlit code:

continent_select = df['continent'].drop_duplicates()
country_select = df['country'].drop_duplicates()

continent_sidebar = st.sidebar.selectbox('Select a continent:', continent_select)
country_sidebar = st.sidebar.selectbox('Select a country:', country_select)

所需输出:我希望特定大陆的国家/地区名称显示在 select 框中,即:Select 'Asia' 来自大陆 select 框。然后在国家 select 框中,香港、中国、印度等...出现。

我尝试将这些行分组到一个包含大洲的列表中

df2 = df.groupby('continent')['country'].apply(list)
continent_sidebar = st.sidebar.selectbox('Select a continent:', df2)

但这会导致 select 框中出现完整列表,即:[卢旺达、摩洛哥、苏丹等]

除了制作字典并手动分组之外,还有更简单的方法吗?

查看代码中的注释。

代码

import streamlit as st
import pandas as pd


data = {
    'country': ['Hong Kong', 'Montenegro', 'Rwanda', 'Myanmar', 'Saudi Arabia'],
    'continent': ['Asia', 'Europe', 'Africa', 'Asia', 'Asia']
}

df = pd.DataFrame(data)

continent_select = df['continent'].drop_duplicates()
# country_select = df['country'].drop_duplicates()

continent_sidebar = st.sidebar.selectbox('Select a continent:', continent_select)

# Get dataframe where continent is the continent_sidebar.
df1 = df.loc[df.continent == continent_sidebar]

# Get the country column from df1.
df2 = df1.country

# Show df2 in the side bar.
country_sidebar = st.sidebar.selectbox('Select a country:', df2)

输出