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