PablocFonseca / streamlit-aggrid

Implementation of Ag-Grid component for Streamlit
https://pypi.org/project/streamlit-aggrid/
MIT License
1.06k stars 202 forks source link

feature request: create new rows interactively #52

Closed Casyfill closed 6 months ago

Casyfill commented 2 years ago

wish/feature request: it would be awesome to be able to add rows to the data frame, treating it as some kind of form

miannini commented 2 years ago

I'm looking forward to see this functionality in place. Would be very useful. any way to include similar buttons on top of the table as in this link: [https://www.ag-grid.com/javascript-data-grid/data-update-transactions/](url).

gchhablani commented 2 years ago

I would love this feature as well! It would be pretty awesome.

aduverger commented 2 years ago

Hello,

With the use of Streamlit cache, you can add a button that append a row to the input dataframe of AfGrid() :

import streamlit as st
import pandas as pd
from pandas.api.types import is_bool_dtype, is_numeric_dtype
from st_aggrid import AgGrid, GridOptionsBuilder

def get_blank_from_dtype(dtype):
    """Return correct values for the new line: 0 if column is numeric, "" if column is object, ..."""
    if is_numeric_dtype(dtype):
        return 0
    elif is_bool_dtype(dtype):
        return False
    else:
        return ""

# Initialize your dataframe
if "df_for_grid" not in st.session_state:
    st.session_state.df_for_grid = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
add_row = st.button("➕ Row")
if add_row:
    st.session_state.df_for_grid = st.session_state.changed_df.append(
        pd.Series(
            [
                get_blank_from_dtype(dtype)
                for dtype in st.session_state.df_for_grid.dtypes
            ],
            index=st.session_state.df_for_grid.columns,
        ),
        ignore_index=True,
    )
gb = GridOptionsBuilder.from_dataframe(st.session_state.df_for_grid)
gb.configure_default_column(editable=True)
gridOptions = gb.build()
grid = AgGrid(
    st.session_state.df_for_grid,
    gridOptions=gridOptions,
)
st.session_state.changed_df = grid["data"]