0

In my code once the user chooses the state from the first dropdown, I want to display counties only from that state in the second dropdown. Currently it always filters the county to Alaska which is the first state listed in the state dropdown.

import streamlit as st
import pandas as pd

st.sidebar.info('### ***US States and Counties***')
    
with st.sidebar:
    # Add a dropdown to select a state
    state_county_data = pd.read_csv("https://raw.githubusercontent.com/kjhealy/us-county/master/data/census/fips-by-state.csv",encoding = 'unicode_escape')
    states = sorted(state_county_data["state"].unique())
    selected_state = st.selectbox("Select a state", states)

    # Use the state code to filter the counties dataframe
    counties = sorted(state_county_data.loc[state_county_data["state"] == selected_state]["name"].unique())

    # Add a dropdown to select a county
    selected_county = st.selectbox("Select a county", counties)

    # Show the selected state and county
    button = st.button('Update')
vvvvv
  • 25,404
  • 19
  • 49
  • 81
user3646519
  • 353
  • 5
  • 15
  • I tried your code and it is happening as intended: when you select a state, it only shows counties from that state. By default, when first loading the page, it shows "AK" and the counties of "Alaska" but you can choose a different default value. see https://stackoverflow.com/a/65145404/5446749 – vvvvv Mar 14 '23 at 16:03
  • I had to upgrade my streamlit version and then it started working, thanks for testing – user3646519 Mar 15 '23 at 12:52
  • what version did you have? – vvvvv Mar 15 '23 at 13:06

0 Answers0