I want to create a website containing a data_editior and two buttons Add(to add a new row at the bottom of the data_editor) and Remove(to delete the row at the bottom of the data_editor) just as shown here:
My code for the same is:
import streamlit as st
import pandas as pd
st.header('Music Recommender System')
col1,col2=st.columns(2)
list=[{'name': 'Love', 'year':1991},
{'name': 'Smells Like Teen Spirit', 'year': 1991},
{'name': 'Lithium', 'year': 1992},
{'name': 'All Apologies', 'year': 1993},
{'name': 'Stay Away', 'year': 1993}]
df=pd.DataFrame(list)
with col1:
edited_df = st.data_editor(df)
with col2:
'#'
Add=st.button("Add")
Remove=st.button("Remove")
#No idea about how to remove the last row
if(Add):
list.append({'name':None,'year':None})
df=pd.DataFrame(list)
with col1:
edited_df = st.data_editor(df)
when I click Add it creates a duplicate table instead of adding a row to the same table as shown here:
Have a look at this. Also added a button to save the dataframe to csv file.
import streamlit as st
import pandas as pd
list = [{'name': 'Love', 'year':1991},
{'name': 'Smells Like Teen Spirit', 'year': 1991},
{'name': 'Lithium', 'year': 1992},
{'name': 'All Apologies', 'year': 1993},
{'name': 'Stay Away', 'year': 1993}]
# Create a variable to hold the dataframe. Initialize it with the given list.
if 'df' not in st.session_state:
st.session_state.df = pd.DataFrame(list)
st.header('Music Recommender System')
col1, col2 = st.columns([2, 1], gap='medium')
with col1:
edited_df = st.data_editor(st.session_state.df, use_container_width=True)
with col2:
Add = st.button("Add")
Remove = st.button("Remove")
save = st.button('Save to data_temp.csv')
if Add:
new_df = pd.DataFrame([{'name':None,'year':None}])
# Add this new_df to the existing st.session_state.df.
st.session_state.df = pd.concat([st.session_state.df, new_df], ignore_index=True)
st.rerun() # to rerender the updated value of st.session_state.df
if Remove:
st.session_state.df = st.session_state.df.drop(st.session_state.df.index[-1])
st.rerun()
if save:
st.session_state['df'].to_csv('data_temp.csv', index=False)
Once your have the csv file, you don’t need the list anymore. You can load the df from a csv file like below.
if 'df' not in st.session_state:
st.session_state.df = pd.read_csv('data_temp.csv')
Thanks a lot brother …I spent endless time in searching for a relevant solution to my problem…Your code really works well…Thanks again for helping me​:people_hugging: