i want a user editable dataframe and a button that saves the current dataframe to a new dataframe and allows for it to be updated based on the highlighted region of a plot
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
# Initialize session state
if 'original_df' not in st.session_state:
# Create sample data
st.session_state.original_df = pd.DataFrame({
'x': np.linspace(0, 10, 50),
'y': np.sin(np.linspace(0, 10, 50)) + np.random.normal(0, 0.1, 50)
})
if 'saved_dfs' not in st.session_state:
st.session_state.saved_dfs = []
st.title("Editable DataFrame with Interactive Plot")
# Display editable dataframe
st.subheader("Original DataFrame")
edited_df = st.data_editor(
st.session_state.original_df,
num_rows="dynamic",
use_container_width=True
)
# Create plot
fig = px.scatter(edited_df, x='x', y='y', title='Interactive Plot')
fig.update_layout(
dragmode='select',
hovermode='closest'
)
# Display plot
selected_points = plotly_chart = st.plotly_chart(fig, use_container_width=True)
# Save button
if st.button("Save Current DataFrame"):
st.session_state.saved_dfs.append(edited_df.copy())
st.success(f"DataFrame saved! Total saved versions: {len(st.session_state.saved_dfs)}")
# Display saved dataframes
if st.session_state.saved_dfs:
st.subheader("Saved DataFrames")
for i, saved_df in enumerate(st.session_state.saved_dfs):
with st.expander(f"Saved DataFrame {i+1}"):
st.dataframe(saved_df)
# Plot for saved dataframe
fig_saved = px.scatter(saved_df, x='x', y='y',
title=f'Plot for Saved DataFrame {i+1}')
st.plotly_chart(fig_saved, use_container_width=True)
# Option to update based on selection
if st.button(f"Update Original with Selected Points (Version {i+1})"):
if selected_points:
# Get selected points indices
points = selected_points.selected_data
if points:
# Update original dataframe with selected points
selected_indices = [point['pointIndex'] for point in points['points']]
st.session_state.original_df = saved_df.iloc[selected_indices].copy()
st.experimental_rerun()
else:
st.warning("Please select points on the plot first")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?