0

I have a df where I've used pycountry to get full names for country column and continent column and make select box in streamlit like so,

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)

Desired output: I would like country names for specific continent to show in select box ie: Select 'Asia' from continent select box. Then in country select box, Hong Kong, China, India, etc... show up.

Streamlit Select Box

I've tried to group the rows into a list with continent

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

But this results in having a full list in the select box ie: [Rwanda, Morocco, Sudan, etc.]

Is there an easier way besides making a dictionary and grouping them manually?

AJ.
  • 19
  • 8

1 Answers1

1

See the comments in the code.

Code

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)

Output

enter image description here

ferdy
  • 4,396
  • 2
  • 4
  • 16
  • That worked. I've used loc to pull up a specific value but not all and match with another column. I could use the same procedure to combine another column ie: 'views', right? – AJ. May 07 '22 at 06:08