AgGrid table not updating with new column

I am trying to create an interactive table using AgGrid. The app allows the user to upload a csv file, and then displays the table. However, when a new column is added, this change is not reflected in the table.

import streamlit as st
import pandas as pd
from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode

def main():
    st.title("CSV Column Adder and Cell Editor")

    # Upload CSV file
    uploaded_file = st.file_uploader("Upload a CSV file", type="csv")

    if uploaded_file is not None:
        # Read the CSV file
        df = pd.read_csv(uploaded_file)
        
        # Initialize session state
        if 'df' not in st.session_state:
            st.session_state.df = df

        # Display editable DataFrame
        st.write("Edit the DataFrame:")
        
        gb = GridOptionsBuilder.from_dataframe(st.session_state.df)
        gb.configure_default_column(editable=True)
        gridOptions = gb.build()
        
        grid_response = AgGrid(
            st.session_state.df,
            gridOptions=gridOptions,
            update_mode=GridUpdateMode.MODEL_CHANGED
        )
        
        st.session_state.df = grid_response['data']
        
        # Button to add a new column
        if st.button("Add a New Column"):
            with st.form("add_column_form"):
                new_column_name = st.text_input("Enter the name of the new column:")
                default_value = st.text_input("Enter the default value for the new column:")
                submitted = st.form_submit_button("Add Column")
                
                if submitted:
                    if new_column_name in st.session_state.df.columns:
                        st.warning("Column already exists!")
                    else:
                        st.session_state.df[new_column_name] = default_value
                        st.success(f"Column '{new_column_name}' added!")
                        st.experimental_rerun()  # Refresh the page to update the grid

if __name__ == "__main__":
    main()

Hi @sakshamyadav

Have you tried using Pandas to add the new column to the DataFrame and save that to a session state variable for the DataFrame. Technically, the updated DataFrame should be displayed in real-time.

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