Adding a new row to a dataframe with each button click (persistent dataframe)

Is there anyway to append a new value to a single column dataframe each time a button is clicked? I have tried to implement it using st.cache but the cached values are those every time the script reruns and not every time the button is pressed. The dataframe is empty initially.

1 Like

Hi @Yashvin_Jagarlamudi :partying_face:. Could you please make available a snipp of you code and a screenshot of the problem you facing, i might be able to help you. Looking over the top of your question, i think it’s a logic problem and nothing correlation with streamlit problem.

Hi @Yashvin_Jagarlamudi, welcome to the Streamlit community!! :tada: :confetti_ball:

Your question sort of sounds like maintaining session state. Maybe take a look at this post or our session-state tag to see if it helps with this problem.

Here’s a simple working example that shows how to grow a dataframe a single row at a time using SessionState and clicking a button:

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


# Create an empty dataframe
data = pd.DataFrame(columns=["Random"])
st.text("Original dataframe")

# with every interaction, the script runs from top to bottom
# resulting in the empty dataframe

# persist state of dataframe
session_state = SessionState.get(df=data)

# random value to append; could be a num_input widget if you want
random_value = np.random.randn()

if st.button("Append random value"):
    # update dataframe state
    session_state.df = session_state.df.append({'Random': random_value}, ignore_index=True)
    st.text("Updated dataframe")

# still empty as state is not persisted
st.text("Original dataframe")

Happy Streamlit-ing! :balloon:

@feliperoque I was trying to do something similar to what @snehankekre has below

1 Like

thank you for help. This is what I was looking for but I couldn’t figure out how to do it in with Session State!