Appending user input data to a df and delete last appended row

Based on the solution from the following link, I have the following code to append user input numbers to a df, and I would like to write a small function to be able to delete last row in case user makes a mistake. The Delete row button doesn’t work. Appreciate any hint on what I am doing wrong.


import streamlit as st

@st.cache(allow_output_mutation=True)
def get_data():
    return []

def drop_last_row(df):
    df = df[:-1]
    return df

time1 = st.number_input("Elapsedtime 1")
time2 = st.number_input("Elapsedtime 2")
value_mean = st.number_input("Mean value")

if st.button("Add row"):
    get_data().append({"Time 1": time1, "Time 2": time2, "Mean Value": value_mean})

if st.button('Delete row'):
    df = get_data()
    drop_last_row(df)
    
df = pd.DataFrame(get_data())
st.write(df)

st.cache is no longer supported by the latest streamlit starting version 1.18.

A possible alternative is to use a session state variable for this particular example.

Example

import streamlit as st
import pandas as pd


if 'data' not in st.session_state:
    st.session_state.data = []


def get_data():
    return st.session_state.data


def drop_last_row():
    st.session_state.data = get_data()[:-1]


time1 = st.number_input("Elapsedtime 1")
time2 = st.number_input("Elapsedtime 2")
value_mean = st.number_input("Mean value")

if st.button("Add row"):
    get_data().append({"Time 1": time1, "Time 2": time2,
                       "Mean Value": value_mean})

if st.button('Delete row'):
    drop_last_row()
    
df = pd.DataFrame(get_data())
st.write(df)

You may experiment with the new caching methods.

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