Apply conversion factor to columns in a dataframe using a button

I’m building an app that imports a csv file containing multiple numeric columns, and the goal once the csv file is imported, is to be able to apply conversion factors to one or more columns. The layout of the app is like this :

Once the csv file is imported, the user can display initial data and perform conversion factors by selecting one or more columns

Basically, I would like to be able to click on the “apply conversion” button and allow the older conversions to remain. I’m aware I need to manipulate session_state in order to make it, but I’m not sure how.

  • The app runs locally
  • streamlit==1.36.0 & Python v 3.10.6

You can try creating a dictionary in Session State with all of your conversion factors.

import streamlit as st

if "factors" not in st.session_state:
    st.session_state.factors = {}

columns = st.multiselect("Columns", options=["A","B","C","D"])
factor = st.number_input("Factor", min_value=0)

if st.button("Apply"):
    for col in columns:
        st.session_state.factors[col] = factor

st.write(st.session_state.factors)

# Apply the saved factors

This snippet replaces the factor for a column if it was previously set, but you could add a few more lines to check if a column already has a factor saved and compound them instead of replace them, if you want.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.