The output does not change as changing the selection

Hi all,

I think this might be a simple issue but I couldn’t find a solution anywhere. I write this code and I just have one function that is dependant on user selection. It is running properly for default selection (Q4_2018) but once I change the selection the output(chart) doesn’t change.
Can someone please advise?
Here is the code:

option_selected=st.selectbox('Which Quarter',[
    'Q4_2018',
    'Q1_2019',
    'Q2_2019',
    'Q3_2019',
    'Q4_2019',
    'Q1_2020',
    'Q2_2020',
    'Q3_2020'])

@st.cache(persist=True)

def country_risk():

    dff = option_selected+'.xlsx'
    data=pd.read_excel(dff, skiprows=(0,1,2,3,4,5,7),skipfooter=3,index_col=0,na_values='-')
    data=data.drop(labels=['World Total','Developed Countries','Emerging Countries','United Arab Emirates'],axis=0)
    data=data.dropna(1,how='all').replace(np.nan, 0)
    knn1=KNN_model.predict(data)
    data['Risk_Category']=knn1

    return data
data=country_risk()

fig = px.choropleth(
        data_frame=data,
        locations=data.index,
        locationmode='country names',
        color='Risk_Category',
        hover_data=['Govt Budg Bal', 'Unemployment Rate',
        'Real GDP', 'CPI','FX Reserves'],
        width=1200, height=1000,
         color_discrete_map={

            "High": "red",
            "Fairly_High": "darkorange",
            "Reasonable": "orange",
            "Satisfactory": "yellow",
            "Low": "yellowgreen",
            "Very_Low": "green"},
        category_orders={"Default Risk": ["Very_Low"
                                           "Low",
                                          "Satisfactory",
                                          "Reasonable",
                                          "Fairly High",
                                          "High"
                                          ]},

        )
fig.update_geos(
        visible=False,showcountries=True)
st.plotly_chart(fig)

From your code, you aren’t passing in an argument to country_risk(), so the first run gets persisted by the cache. You can try modifying your code as the following:

@st.cache(persist=True)
def country_risk(option_selected):

    dff = option_selected+'.xlsx'
    data=pd.read_excel(dff, skiprows=(0,1,2,3,4,5,7),skipfooter=3,index_col=0,na_values='-')
    data=data.drop(labels=['World Total','Developed Countries','Emerging Countries','United Arab Emirates'],axis=0)
    data=data.dropna(1,how='all').replace(np.nan, 0)
    knn1=KNN_model.predict(data)
    data['Risk_Category']=knn1

    return data
data=country_risk(option_selected)

Best,
Randy

1 Like