Hi, I am trying to use the selectbox function in my project with the following workflow :
get value from sqlite database
convert a column into a list
get a value with a selectbox function
use this value into another âselect statementâ
The code i wrote works well for the first element of the list, but as soon as I change the value with the dropdown list, I get an error really not explicit. Here is my code :
import streamlit as st
import pandas as pd
import sqlite3
conn = sqlite3.connect('myDB.db') # Connection / Creation of the DataBase
c = conn.cursor()
conn.commit()
df1 = pd.read_sql_query('select col1, col2 '
'from "myTable1" , conn)
list = df1['col1'].to_list()
selection = st.selectbox('Choose value :', list)
get_id = df1['col2'].loc[df1['col1'] == selection][0]
df2 = pd.read_sql_query('SELECT * FROM myTable2 WHERE ID = ' + str(get_id ), conn)
st.dataframe(data=df2)
And the error I get is simply
KeyError: 0
Traceback:
It says the error is at this level : get_id = df1[âcol2â].loc[df1[âcol1â] == selection][0] but to my mind this is good because it runs well with the first element of the list and as I said : I only have the error when I change the value of the selectbox.
Here with [0] youâre subsetting the first row of df1, thatâs why you get KeyError, get_id canât ever return anything other than the first entry.
Also not a good idea to be using .loc on a column, can you write down what your filtering criteria should be?
Thank you very much for this quick answer. What was weird is that I do had the good value when I ran my code through the debug mode.
But itâs clearn now! Thank you again
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking âAccept allâ, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.