Cant remove cache warning and other errors

Hi, have not used Streamlit for a year or so.
Today i resumed my Streamlit journey and encountered few issues.
Issue#1 -

filter_columns = {
    "PuRegion": "Region",
    "PuMarket": "Market",
    "PuState": "State",
    "DelState": "DelState",
#    "PuDay": "Day",
#    "PuMonth": "Month",

}
st.sidebar.header("Choose your filter")

# Loop through all the columns
filtered_df = df.copy()
for column, prompt in filter_columns.items():
    choices = st.sidebar.multiselect(f"Pick your {prompt}", options=sorted(set(filtered_df[column].values)))
    if choices:
        filtered_df = filtered_df[filtered_df[column].isin(choices)]

This is my search bar - had to specify each of my searchable things as string format but could not do with the PuDay and PuMonth.
Had to comment out and try to find solution solution.
This is what i get:

TypeError: '<' not supported between instances of 'float' and 'str'
Traceback:

File "/development/koala/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/exec_code.py", line 88, in exec_func_with_error_handling
    result = func()
             ^^^^^^
File "/development/koala/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 590, in code_to_exec
    exec(code, module.__dict__)
File "/development/koala/1_Home.py", line 515, in <module>
    choices = st.sidebar.multiselect(f"Pick your {prompt}", options=sorted(set(filtered_df[column].values)))
                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

And this is my date format:

    df['PuDate'] = pd.to_datetime(df['PuDate'])     # skip if your Date column already in datetime format
    df['PuWeekDay'] = df['PuDate'].dt.weekday
    df['PuMonth'] = df['PuDate'].dt.month # dt.month - if i have issues with groupby() method !
    df['PuYear'] = df['PuDate'].dt.year
    df['PuWeek'] = df['PuDate'].dt.strftime('%W')   # Important to get day of the week 
    df['PuDay'] = df['PuDate'].dt.strftime('%A')

Looking for solution as this is a key part to me. Its filters by day ( mon, tue etc) and month ( jan, feb. etc. )
I thought it was formatted before with dt.strftime before this code is run.

Issue#2

CachedWidgetWarning: Your script uses a widget command in a cached function (function decorated with @st.cache_data or @st.cache_resource). This code will only be called when we detect a cache "miss", which can lead to unexpected results.

To fix this, move all widget commands outside the cached function.
Traceback:

File "/usr/lib/python3.12/threading.py", line 1032, in _bootstrap
    self._bootstrap_inner()
File "/usr/lib/python3.12/threading.py", line 1075, in _bootstrap_inner
    self.run()
File "/usr/lib/python3.12/threading.py", line 1012, in run
    self._target(*self._args, **self._kwargs)
File "/development/koala/1_Home.py", line 1247, in <module>
    main()
File "/development/koala/1_Home.py", line 662, in main
    st_map = map_display(filtered_df)
File "/development/koala/1_Home.py", line 586, in map_display
    st_map = st_folium(m, returned_objects=[], use_container_width=True)
File "/development/koala/lib/python3.12/site-packages/streamlit_folium/__init__.py", line 402, in st_folium
    component_value = _component_func(

Tried this:

[client]
showErrorDetails = false

and this:
streamlit run app.py --client.showErrorDetails=false
Still showing.
Im running folium map under @st.cache_data as if my memory recalls - its faster as im running csv file with 6k rows and plenty of columns and they represents my data under folium map. plus actual app is close to 1200 lines.

Ive installed latest streamlit few days ago. Running on Linux. Python 3.12.5
Thank You!

1 Like

Hey @kodasopen, I have searched for the error of the first issue and it sounds like your dataframe columns contains mixed datatypes. You probably have to make sure that the values are casted to the same type (all str or all float) before applying sorted.

For the second issue, I believe you should only cache the expensive operation that you then pass to the folium component. I don’t know this part of your code, but instead of

@st.cache_resource
def render_folium(input):
  res = expensive_operation(input)
  st.folium(res)

render_map("my_input")

you should to

@st.cache_resource
def compute_folium_input(input):
  return expensive_operation(input)

res = compute_folium_input("my_input")
st.folium(res)

The st.folium command itself should hopefully be performant and only send some data over the wire and the web component should only be re-rendered if the sent data changes, if the component is written correctly.

I believe the problem with having a widget inside of a cached function is that, if the function body is not executed due to a cache hit, the widget will disappear from the website because the backend won’t re-send the component delta to the webapp for a rerun and the webapp will assume that it is stale.

1 Like

Thanks for your help.
Yes, first one turns out was as you say - mixed type.
Second one.

@st.cache_resource
def map_display(filtered_df):
    m = folium.Map(location=[38, -96.5], zoom_start=5, scrollWheelZoom=False)

    choropleth = folium.Choropleth(
        geo_data='us-state.geojson',
        data=filtered_df,
        columns=['PuState', 'StateRPM'],
        key_on='feature.properties.stusab',
        legend_name="rpm",
        fill_color='BuGn',
        highlight=True
    ).add_to(m)
    #Plenty of options for map
    st_map = st_folium(m, returned_objects=[], use_container_width=True)

and then:

def main()
    st_map = map_display(filtered_df)
if __name__ == '__main__':
    main()
1 Like