Data Frame question in selectbox

Hi All,

Working on a project here: https://desolate-ocean-14363.herokuapp.com/

I’m trying to python my way through as an easy button, but here’s the situation.
Restaurant names are selected, and the name is used to do a df.loc[‘name’] and pull up the stats for the restaurant. The problem is some restaurants show up more than once in a NYC borough, like “Sweet Chick”, and this will cause an error as pandas can’t pick just one. So I created an index for the data frame, and I want pandas to select the entry by index, but in the selectbox, to keep the user experience friendly, I want to retain the name.

Here’s what my dataframe looks like:

I was curious if you can think of a way to python around this, or are aware of any additional parameters to st.selectbox that i might not be aware of that will accept the name, as well as the index location.
Currently, I have it set up to populate the selectbox with a list of the restaurant names, and also as an experiment, to just use the restaurant name as index to populate the select box.
Github is here: https://github.com/hamiltonchangcodes/yelp_report_cards/tree/master/frontend

Thanks in advance!!

  • Hamilton

yes, this can be done using format_funct and lambda functions. Have a look at
@Jonathan_Rhone s answer to my similar question: Label and values in in selectbox.

Thanks for the reply godot63! This is actually very cool to know, but I don’t want to actually display the number…

I want to store it for an df.iloc so i don’t have to manually rename the duplicates, just do an index based access. Code below for what I intend.

I’m thinking about how i might be able to make this work, it could work with some wrangling maybe? Either that or maybe i’m just not comprehending the full utility of format_func

I tried to make an example that comes closer to what you are describing, just run the following code:

import streamlit as st
import pandas as pd

# initialize list of lists
data = [['Le goumet', 10], ['The Alcove', 15], ['Mojo Restaurant', 14], ['Mojo Restaurant', 1]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'ID'])

values = df['Name'].tolist()
options = df['ID'].tolist()
dic = dict(zip(options, values))

a = st.sidebar.selectbox('Choose a restaurant', options, format_func=lambda x: dic[x])

st.write(a)

The select box shows names, but when selecting an item, a number is returned. The trick is not create a dictionary with names and respective ids. it also works if 2 names are identical. I hope this is what you were looking for.

2 Likes

godot63. I see now what you mean. You’re a wizard thank you so much!!!

1 Like

You are welcome. Wizard apprentice I would rather say, the wizard was @Jonathan_Rhone who answered my very similar question originally :grinning:

1 Like