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 

# https://gist.githubusercontent.com/tvst/036da038ab3e999a64497f42de966a92/raw/f0db274dd4d295ee173b4d52939be5ad55ae058d/SessionState.py

# 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
st.dataframe(data) 

# 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")
    st.dataframe(session_state.df)

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

Happy Streamlit-ing! :balloon:
Snehan

@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!

2 Likes