Home > Software design >  Streamlit - IF statement depending on text_input
Streamlit - IF statement depending on text_input

Time:06-17

There is an error message (KeyError: '') for line 25,26 when the text inputs are empty but I can't manage to get rid of it. I want the variables Vec1 and Vec2 to be stored only when there exists a text input for both widgets. To run the code, you can load any xlsx table, like this one:

Var1 Var2
5 7
6 8

Here is my code

import numpy as np 
import pandas as pd
import streamlit as st

st.set_page_config(layout="wide")

#Import file
xlsx_file = st.sidebar.file_uploader('Import File', type = 'xlsx') 

#Select Variables of interest
Vec1Name = st.sidebar.text_input("First Variable Name")
Vec2Name = st.sidebar.text_input("Second Variable Name")

st.title('Data')
col1, col2 = st.columns((3,1))

if xlsx_file is not None:
    df = pd.read_excel(xlsx_file)
    col1.write(''' #### Dataframe''')
    col1.write(df)
    
    if all(var is not None for var in [Vec1Name, Vec2Name]):
        
        #Store Variables
        Vec1 = df[str(Vec1Name)]
        Vec2 = df[str(Vec2Name)]

        #Variables of Interest
        col2.write(''' #### Variables of Interest''')
        col2.write(df[[str(Vec1Name),str(Vec2Name)]])

Thank you for your help!

CodePudding user response:

The error you're facing is because the text_input can not be found within df. If you know already that you want the input to be amongst the columns, why not use st.selectbox instead, and specify df.columns as options? Let me know if that code works better:

import numpy as np 
import pandas as pd
import streamlit as st

st.set_page_config(layout="wide")

#Import file
xlsx_file = st.sidebar.file_uploader('Import File', type = 'xlsx') 

st.title('Data')
col1, col2 = st.columns((3,1))

if xlsx_file is not None:

    df = pd.read_excel(xlsx_file)

    #Select Variables of interest
    Vec1Name = st.sidebar.selectbox("First Variable Name", df.columns)
    Vec2Name = st.sidebar.selectbox("Second Variable Name", df.columns)

    col1.write(''' #### Dataframe''')
    col1.write(df)
        
    #Store Variables
    Vec1 = df[str(Vec1Name)]
    Vec2 = df[str(Vec2Name)]

    #Variables of Interest
    col2.write(''' #### Variables of Interest''')
    col2.write(df[[str(Vec1Name),str(Vec2Name)]])
  • Related