Newb to Streamlit, easy Selectbox question I am sure

So I am new to Streamlit, and had a question that I could not find the answer to within the community pages (some were close). So why not post my first question?!? I am creating a multipage project map application from a CSV file. Pretty simple stuff.

I have a data frame that reads just fine, and the third column header is Office and it has generic office locations like Denver, or New York.

I created a st.sidebar.selectbox with those unique instances (33 in total) there.

I thought I would be able to have it select the appropriate df to display, but can not wrap my head around the selectbox and how to make it work. I just want my end user to select the office and it display the df for that query.

I would love to have some direction on this as I am banging my head against the wall here trying to sort this out. Could be I overlooked something entirely (which happens often sadly).

Thanks in advance…

Hey Justin
You can store the selected output from the selectbox in a variable (let’s call it option)
Then you can create a button beneath it like -

if st.button("Select"):
      # here you can write the logic to select the data with specified offices
      new_df = df[df.Office == option]
      # now you can output the new_df on screen
1 Like

Hi @andthisjustin

If you have disparate dataframes, you could append them to a list and then show them programmatically using the index of the list.

However, I suspect that you are reading data from a single dataframe with different Office values. The way I would do this is:

  1. Using pandas, read the unique Office values in the sidebar selectbox widget
  2. Basis the user selection of this selectbox widget, query the same dataframe with pandas to show offices whose values = the widget value
  3. If you want your selectbox widget to show text in a format as All Offices, you can append the pre (All ) and post ( Offices) text during the execution of point #1 above. And reverse the process (using replace with blank), when you are running step #2

Hope this helps,

Cheers

1 Like

Thank you @Kanak & @Shawn_Pereira for the insight. I was able to accomplish it with the following code…

select_offices = st.sidebar.selectbox(“Select office to display data from:”, sorted(pd.unique(df[‘Office’])))

Worked like a charm!

-justin

@Shawn_Pereira (or anyone for that matter),

I had a question about your comment, specifically #3. I am finally circling back to this, and thought I understood, but unfortunately I do not.

Below is a snippet of my selectbox as of today and its not wanting to play nicely when I try to have it sort values as seen below (All Offices, All Canada Offices, etc.,). It works perfectly when selecting just an individual offices from the list and displaying that data frame and map.

I have looked at it, banged my head a little and still can not see my error. May I ask what I might have done incorrectly? Never really tackled if/else statements in python before.

Thanks in advance!

    select_office_dropdown = [' ']+ ['All Offices']+ ['All Canada Offices']+ ['All Latin America Offices']+ ['All US Offices']+ list(df['Office'].drop_duplicates().sort_values())
    select_office = st.sidebar.selectbox("Select office to display data from:", select_office_dropdown)

    if select_office_dropdown == 'All Offices':
        st.write(df.query(list(df['Office'].sort_values(by=[2]))))

    elif select_office_dropdown == 'All Canada Offices':
        st.write(df.query(list(df['Office'].sort_values(by=['Toronto', 'Ottawa']))))

    elif select_office_dropdown == 'All Latin America Offices':
        st.write(df.query(list(df['Office'].sort_values(by=["Mexico", "Guatemala"]))))    

    else select_office_dropdown == 'All US Offices':
        st.write(df.query(list(df['Office'].sort_values(by=["Atlanta", "Chicago"]))))

    st.dataframe(df.filter(["Project Number", "Project Name", "Office"]).loc[(df["Office"] == select_office) & (df["Year"] == select_year)].reset_index(drop=True),)

Hi @andthisjustin , there are multiple ways you can go about. I have highlighted one of the ways I was talking about earlier. Replicate this on your system and test that it is working, before modifying it suitably for your future use.

The data I used is as a CSV file (projects.csv):
tstdf

[pre]
vpth = “D:/ShawnP/Python/adhoc tst prgs/” # change this to your local path
vcsv = “projects.csv” # change this to your CSV file name w/extn

df = pd.read_csv(vpth + vcsv)
try:
location_list = pd.Series(df[“Location”]).unique().tolist()
location_list = [“All " + x + " Offices” for x in location_list] # add prefix/postfix of All & Offices respectively
location_list.insert(0, “”) # add 1st blank entry so that 1st option does not get auto selected

chosen_office_location = st.sidebar.selectbox("Select Offices to display from", location_list)
if chosen_office_location != "":
    chosen_office_location = chosen_office_location.replace("All ", "").replace(" Offices", "")  # strip prefix/postfix added earlier
    st.write(f"You chose {chosen_office_location}")

    # choose which fields you want and in what order; similarly, you can also choose the filter condition
    tdf = df.get(['ProjectName', 'Office', 'Location']).where(df.get("Location") == chosen_office_location).dropna().sort_values(by="Office")
    st.dataframe(tdf)

except:
st.error(f"Can’t find file: {vcsv} at location: {vpth}")
[/pre]

Cheers :slight_smile:
PS: My code indenting goes off when I paste here; I trust you can change it at your end.

1 Like

Thank you very much @Shawn_Pereira! I am sorry for the delayed reply, it took a few days for me to circle back to this and configure for my workflow.

Again, thank you very much, you certainly helped me solve this roadblock!

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.