Implementation of Ag-Grid component for Streamlit

Overview

streamlit-aggrid

Open in Streamlit GitHub PyPI

AgGrid is an awsome grid for web frontend. More information in https://www.ag-grid.com/. Consider purchasing a license from Ag-Grid if you are going to use enterprise features!

Comment on discuss.streamlit.io If you like it or Buy me a beer 🍺 !


Install

pip install streamlit-aggrid

Quick Use

Create an example.py file

from st_aggrid import AgGrid
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/airline-safety/airline-safety.csv')
AgGrid(df)

Run :

streamlit run example.py

Demo

Grid data is sent back to streamlit and can be reused in other components. In the example below a chart is updated on grid edition.

example image

Develop

ment Notes Version 0.2.2

  • Updated frontend dependencies to latest version
  • Corrected text color for better viz when using streamlit theme (thanks jasonpmcculloch)
  • Switched default theme to Balham Light ('light'), if you want to use streamlit theme set theme='streamlit' on agGrid call

Version 0.2.0

  • Support Themes
  • Incorporated Pull Requests with fixes and pre-select rows (Thanks randomseed42 and msabramo)
  • You can use strings instead of importing GridUpdateMode and DataReturnMode enumerators
  • it works fine with st.forms!
  • new theme example in example folder

Version 0.1.9

  • Small fixes
  • Organized examples folder

Version 0.1.8

  • Fixes a bug that breaks the grid when NaN or Inf values are present in the data

Version 0.1.7

  • Fixes a bug that happened when converting data back from the grid with only one row
  • Added license_key parameter on AgGrid call.

Version 0.1.6

  • Fixes issue #3
  • Adds support for timedelta columns check example

Version 0.1.5

  • small bug fixes
  • there is an option to avoid grid re-initialization on app update (check fixed_key_example.py on examples folder or here)

Version 0.1.3

  • Fixed bug where cell was blank after edition.
  • Added enable_enterprise_modules argument to AgGrid call for enabling/disabling enterprise features
  • It is now possible to inject js functions on gridOptions. Enabling advanced customizations such as conditional formating (check 4th column on the example)

Version 0.1.2

  • added customCurrencyFormat as column type

Version 0.1.0:

  • I worked a little bit more on making the example app functional.
  • Couple configuration options for update mode (How frontend updates streamlit) and for data returns (grid should return data filtered? Sorted?)
  • Some basic level of row selection
  • Added some docstrings specially on gridOptionsBuilder methods
  • Lacks performance for production. JS Client code is slow...
Comments
  • Python - Streamlit - Your app is having trouble loading the st_aggrid.agGrid component.

    Python - Streamlit - Your app is having trouble loading the st_aggrid.agGrid component.

    I am facing the same issue:

    Your app is having trouble loading the st_aggrid.agGrid component.

    (The app is attempting to load the component from , and hasn't received its "streamlit:componentReady" message.)

    If this is a development build, have you started the dev server? If this is a release build, have you compiled the frontend?

    Upgrading via "pip install streamlit-aggrid --upgrade" to streamlit-aggrid 0.1.7 didn't help. Please suggest.

    opened by Es-Be 13
  • Hyperlinks in column cells stopped working recently

    Hyperlinks in column cells stopped working recently

    I have been successfully using this very useful package, and until recently could implement hyperlinks in a column with the code:

    gb.configure_column("ISSUE", headerName="ISSUE", cellRenderer=JsCode('''function(params) {return '<a href="https://thebcd.co.uk/issue_' + params.value + '" target="_blank">'+ params.value+'</a>'}'''), width=300)

    which would result in a hyperlink to an address related to the cell value.

    On editing a different part of of my app, I now find that instead of creating a hyperlink to the address, the html text is written to the screen instead:

    <a href="https://thebcd.co.uk/issue_1" target="_blank">1</a>

    rather than the hyperlink 1 to the address. Any help appreciated.

    opened by dajavous 8
  • Have hyperlinks as cell entries in ag-grid through python

    Have hyperlinks as cell entries in ag-grid through python

    I was wondering if there was a way to have hyperlinks as cell entries in ag-grid through python alone. I am trying to display a table where the cell entries would be clickable links and I would like to accomplish this entirely through the python script. Is this something that is currently available or are there known solutions? Thank you!

    opened by gyanendrasharma 7
  • Your app is having trouble loading the st_aggrid.agGrid component.

    Your app is having trouble loading the st_aggrid.agGrid component.

    I am using AgGrid 0.0.7 , streamlit v0.73

    Your app is having trouble loading the st_aggrid.agGrid component.

    (The app is attempting to load the component from , and hasn't received its "streamlit:componentReady" message.)

    If this is a development build, have you started the dev server? If this is a release build, have you compiled the frontend? For more troubleshooting help, please see the Streamlit Component docs or visit our forums.

    this happen when i use call the aggrid function:

    gb = GridOptionsBuilder(min_column_width=100, editable_columns=False, side_panel=False)
        gb.build_columnsDefs_from_dataframe(input_df) #take df as parameters
        gridOptions = gb.build()
    
    
        st.markdown("""
        ## Details#
        """)
    
        grid_response = AgGrid(input_df, gridOptions=gridOptions, height=500)
    
        input_df = grid_response['data']
    
    

    and it seems i continously call the function but i cannot find the "streamlit:componentReady"** message location. can you givve an hints>

    opened by apexbb 7
  • Add custom CSS classes to AgGrid constructor

    Add custom CSS classes to AgGrid constructor

    Hi @PablocFonseca ,

    first all, thanks for this component!

    I would like to apply conditional formatting to rows in the grid using the rowClassRules grid option. From the documentation, I think this is the correct way to apply conditional formatting to rows, please let me know if there is another way that I'm not aware of.

    When I add rowClassRules via the gridOptionsBuilder, the classes are applied correctly to the respective rows, but the styling is not. This is because the html added with st.markdown is added to the main page and the component is rendered in an iframe that does not have access to the parent page's CSS.

    I think a solution would be to provide the custom classes to the AgGrid constructor that then adds them to the iframe page's styles. Is this something you would be open to adding?

    Here's an example app with my simplified use case to illustrate:

    import datetime
    
    import numpy as np
    import pandas as pd
    import streamlit as st
    from st_aggrid import AgGrid, GridOptionsBuilder
    
    
    styles = """
    <style>
    .trade-buy-green {
        color: green
    }
    .trade-sell-red {
        color: red
    }
    </style>
    """
    st.markdown(styles, unsafe_allow_html=True)
    
    now = int(datetime.datetime.now().timestamp())
    start_ts = now - 3 * 30 * 24 * 60 * 60
    
    
    @st.cache
    def make_data():
        df = pd.DataFrame(
            {
                "timestamp": np.random.randint(start_ts, now, 20),
                "side": [np.random.choice(["buy", "sell"]) for i in range(20)],
                "base": [np.random.choice(["JPY", "GBP", "CAD"]) for i in range(20)],
                "quote": [np.random.choice(["EUR", "USD"]) for i in range(20)],
                "amount": list(
                    map(
                        lambda a: round(a, 2),
                        np.random.rand(20) * np.random.randint(1, 1000, 20),
                    )
                ),
                "price": list(
                    map(
                        lambda p: round(p, 5),
                        np.random.rand(20) * np.random.randint(1, 10, 20),
                    )
                ),
            }
        )
        df["cost"] = round(df.amount * df.price, 2)
        df.insert(
            0,
            "datetime",
            df.timestamp.apply(lambda ts: datetime.datetime.fromtimestamp(ts)),
        )
        return df.sort_values("timestamp").drop("timestamp", axis=1)
    
    
    df = make_data()
    gb = GridOptionsBuilder.from_dataframe(df)
    
    row_class_rules = {
        "trade-buy-green": "data.side == 'buy'",
        "trade-sell-red": "data.side == 'sell'",
    }
    gb.configure_grid_options(rowClassRules=row_class_rules)
    grid_options = gb.build()
    
    st.title("rowClassRules Test")
    AgGrid(df, theme="streamlit", gridOptions=grid_options)
    
    opened by ljnsn 5
  • The cells are empty when the columns of the dataframe contains '.'

    The cells are empty when the columns of the dataframe contains '.'

    This issue can be reproduced as the following sample code. Whether display or editing, the cell contents are always empty.

    import pandas as pd import streamline as st from st_aggrid import AgGrid

    df_template = pd.DataFrame( '', index=range(10), columns=['a.b', 'b.c', 'cd'] )

    def cb(r=None): st.write(r['data'])

    with st.form('example form') as f: st.header('Example Form') response = AgGrid(df_template, editable=True, fit_columns_on_grid_load=True) st.form_submit_button(on_click=cb, kwargs=dict(r=response))

    st.write(response['data'])

    def form_callback(): st.write(st.session_state.my_slider) st.write(st.session_state.my_checkbox)

    with st.form(key='my_form'): slider_input = st.slider('My slider', 0, 10, 5, key='my_slider') checkbox_input = st.checkbox('Yes or No', key='my_checkbox') submit_button = st.form_submit_button(label='Submit', on_click=form_callback)

    opened by tonylegend 5
  • Getting AggGrid's state

    Getting AggGrid's state

    Hey @PablocFonseca, thank you for such an amazing job on integrating AggGrid in Streamlit, I highly appreciate the efforts and happy to contribute if there are any known issues that need help from python side of things.

    One task I am having hard time to wrap my head around is getting AggGrid state after a user interacts with it.

    I.e., I have a multi-select to keep grouping consistent between page reloads or new data push.

    # let user pick cols from dataframe she want to group by
    if st.sidebar.checkbox("Enable default grouping"):
        default_group_col = st.sidebar.selectbox("Default group by: ", cols, 1)
    
    # if any of columns are selected, apply it to aggrid and persist on page reload,
    # as default_group_col state is persisted under the hood by streamlit
    try:
        gb.configure_column(default_group_col, rowGroup=True)
    except:
        pass
    

    Now say a user groups by an additional column using AggGrid groupby feature, collapses some of the resulting groups and keeps the others expanded. I would assume AggGrid itself stores this state somewhere in client side JS. Is there a potential way to get stat state back to python in order to save it somewhere in a dict and persist between page reloads when AggGrid component is being redrawn or populated with new data?

    Thanks!

    opened by adamlansky 5
  • Data completely reloads with sorting/filtering interaction with version >=0.3.0

    Data completely reloads with sorting/filtering interaction with version >=0.3.0

    With streamlit-aggrid==0.3.0 or higher and almost any recent version of streamlit, inluding streamlit==0.15.1 , if you have an app that uses a submit button, then the table will disappear when you e.g. try to sort it.

    This does not occur with streamlit-aggrid=0.2.3.

    Here is a minimal example:

    import streamlit as st
    import pandas as pd
    from st_aggrid import AgGrid
    import numpy as np
    
    submit = st.button('Submit', key="submit")
    
    if submit:
        data = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
    else:
        data = None
    
    if data is not None:
        AgGrid(data)
    

    More testing shows even just a simple app will result in completely reloading all the data with interactions.

    from st_aggrid import AgGrid
    import pandas as pd
    
    data = pd.DataFrame([[1,2,3,4],[2,3,4,5]], columns=list('ABCD'))
    
    x = AgGrid(data)
    opened by gregd33 4
  • Clicking a row in streamlit 0.84 causes a TypeError

    Clicking a row in streamlit 0.84 causes a TypeError

    Upgrading to the newly released streamlit 0.84, if I click a row in the grid, I get a TypeError exception:

      File "/Users/abramowi/python/virtualenvs/AppenUploader-UHtnTuBj/lib/python3.8/site-packages/st_aggrid/__init__.py", line 173, in AgGrid
        frame = pd.DataFrame(component_value["rowData"])
    TypeError: string indices must be integers
    
    opened by msabramo 4
  • How to scroll to selected rows?

    How to scroll to selected rows?

    In my application I have a quite large dataframe with a group of selected rows. With: gb.configure_selection(selection_mode="multiple", use_checkbox=True, pre_selected_rows=pre_selected_rows) it is possible to pre-select the rows but I could not figure out how to automatically scroll the view to show the rows.

    The Aggrid API does have the functionality to scroll to a certain Row here. I tried to use this in javascript callbacks but I could not get it to work.

    opened by thunderbug1 3
  • get selectected row_index

    get selectected row_index

    Great tool !

    When using configure_selection, it would be nice to get not only the selected rows but also the selected indices.

    gb.configure_selection(selection_mode="multiple", use_checkbox=False,  pre_selected_rows=[selectedinx])
    gridOptions = gb.build()
    data = AgGrid(
            shows,
            gridOptions=gridOptions,
            allow_unsafe_jscode=True,
            update_mode=GridUpdateMode.SELECTION_CHANGED 
        )
    

    Example of returned data expected

    { "data" : myPandasDataFrame,
    "selected_rows : [ {myselectedRow1},{myselectedRow2}],
    "selected_indices" : [ 4, 8 ]
    } 
    

    I use Aggrid to select a row, then display it and edit, and then I went to move to the next row, which requires to know the indice of selected row

    Thanks

    enhancement 
    opened by nathalieGG 3
  • Bug: rows selected lags behind

    Bug: rows selected lags behind

    I want to select multiple rows. But when get selected_rows it looks like the selection lags behind. Looks to me for every selection i make table send two events, the original/old situation and the new situation. Also ot looks like the table keeps updating and looping.

    Is this a bug? What is the correct way to do this?

    gb = GridOptionsBuilder.from_dataframe(df) gb.configure_default_column(hide=True) gb.configure_column("name",hide=False,width=300,tooltipField="name", headerCheckboxSelection=True )
    gb.configure_column("branch",hide=False,width=150)
    gb.configure_column("startDate",hide=False,width=90,type=["customDateTimeFormat"]) gb.configure_column("endDate",hide=False,width=90,type=["customDateTimeFormat"]) gb.configure_column("roles",hide=False,width=300,tooltipField="roles")
    gb.configure_pagination(enabled=True,paginationPageSize=10,paginationAutoPageSize=False) gb.configure_selection(use_checkbox=True, selection_mode='multiple', pre_selected_rows=selected_rows ) gb.configure_grid_options(tooltipShowDelay=500)

    table = AgGrid(df, gridOptions=gb.build(), enable_enterprise_modules=False, update_mode=GridUpdateMode.SELECTION_CHANGED )

    selected_rows = [item['_selectedRowNodeInfo']['nodeRowIndex'] for item in table.selected_rows] st.session_state[selected_name] = selected_rows

    opened by Tauvic 0
  • Row auto height to show long text

    Row auto height to show long text

    Hi, I'm working with quite long texts and I would like to know if there is any option to resize the rows automatically, so that the full text within a cell is showed. Like this (simple example using st.table):

    Screenshot 2022-12-30 at 15 50 52

    Best regards and thanks for the this component!

    opened by miguelwon 0
  • V.03 theme no longer available in AgGrid

    V.03 theme no longer available in AgGrid

    Code works fine in 2.3 but not in 3 .. can you theme to the config file in V3?

    ValueError: light is not valid. Available options: {'STREAMLIT': <AgGridTheme.STREAMLIT: 'streamlit'>, 'ALPINE': <AgGridTheme.ALPINE: 'alpine'>, 'BALHAM': <AgGridTheme.BALHAM: 'balham'>, 'MATERIAL': <AgGridTheme.MATERIAL: 'material'>} File "C:\Users\sstapinski\pollen\lib\site-packages\st_aggrid__init.py", line 295, in AgGrid raise ValueError(f"{theme} is not valid. Available options: {AgGridTheme.members__}") streamlit-aggrid==0.3.3

    
    import streamlit as st
    import pandas as pd
    import numpy as np
    
    from st_aggrid import AgGrid, GridOptionsBuilder
    
    df = pd.DataFrame(
        np.random.randint(0, 100, 50).reshape(-1, 5),
        index=range(10),
        columns=list("abcde"),
    )
    
    available_themes = ["streamlit", "light", "dark", "blue", "fresh", "material"]
    selected_theme = st.selectbox("Theme", available_themes)
    
    gb = GridOptionsBuilder.from_dataframe(df)
    if st.checkbox('Pre-select rows 4 and 6 when loading.'):
        gb.configure_selection('multiple', pre_selected_rows=[3,5])
    
    response = AgGrid(
        df,
        editable=True,
        gridOptions=gb.build(),
        data_return_mode="filtered_and_sorted",
        update_mode="no_update",
        fit_columns_on_grid_load=True,
        theme=selected_theme
    )
    
    opened by nafets33 0
  • Example Code for MouseOver Tooltip inside of a table

    Example Code for MouseOver Tooltip inside of a table

    Hey there,

    i tried to find something in the dokumentation but cant solve my problem. I want to display an image when you hover over one of the rows but cant find to do how.

    grafik

    Could you add an example?

    opened by Keldorb 0
  •  iteritems is deprecated and will be removed in a future version

    iteritems is deprecated and will be removed in a future version

    Python ver 3.11.0 streamlit-aggrid ver 0.3.3

    When I'm running my app,the terminal dispaly this promption: "site-packages\st_aggrid_init_.py:42: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead."

    opened by la2yyu 0
Streamlit App For Product Analysis - Streamlit App For Product Analysis

Streamlit_App_For_Product_Analysis Здравствуйте! Перед вами дашборд, позволяющий

Grigory Sirotkin 1 Jan 10, 2022
the code for our CVPR 2021 paper Bilateral Grid Learning for Stereo Matching Network [BGNet]

BGNet This repository contains the code for our CVPR 2021 paper Bilateral Grid Learning for Stereo Matching Network [BGNet] Environment Python 3.6.* C

3DCV developer 87 Nov 29, 2022
Official code for On Path Integration of Grid Cells: Group Representation and Isotropic Scaling (NeurIPS 2021)

On Path Integration of Grid Cells: Group Representation and Isotropic Scaling This repo contains the official implementation for the paper On Path Int

Ruiqi Gao 39 Nov 10, 2022
PyTorch implementation for the visual prior component (i.e. perception module) of the Visually Grounded Physics Learner [Li et al., 2020].

VGPL-Visual-Prior PyTorch implementation for the visual prior component (i.e. perception module) of the Visually Grounded Physics Learner (VGPL). Give

Toru 8 Dec 29, 2022
DCA - Official Python implementation of Delaunay Component Analysis algorithm

Delaunay Component Analysis (DCA) Official Python implementation of the Delaunay

Petra Poklukar 9 Sep 6, 2022
DI-HPC is an acceleration operator component for general algorithm modules in reinforcement learning algorithms

DI-HPC: Decision Intelligence - High Performance Computation DI-HPC is an acceleration operator component for general algorithm modules in reinforceme

OpenDILab 185 Dec 29, 2022
Vertical Federated Principal Component Analysis and Its Kernel Extension on Feature-wise Distributed Data based on Pytorch Framework

VFedPCA+VFedAKPCA This is the official source code for the Paper: Vertical Federated Principal Component Analysis and Its Kernel Extension on Feature-

John 9 Sep 18, 2022
Code to reproduce the results in the paper "Tensor Component Analysis for Interpreting the Latent Space of GANs".

Tensor Component Analysis for Interpreting the Latent Space of GANs [ paper | project page ] Code to reproduce the results in the paper "Tensor Compon

James Oldfield 4 Jun 17, 2022
Neon: an add-on for Lightbulb making it easier to handle component interactions

Neon Neon is an add-on for Lightbulb making it easier to handle component interactions. Installation pip install git+https://github.com/neonjonn/light

Neon Jonn 9 Apr 29, 2022
A Home Assistant custom component for Lobe. Lobe is an AI tool that can classify images.

Lobe This is a Home Assistant custom component for Lobe. Lobe is an AI tool that can classify images. This component lets you easily use an exported m

Kendell R 4 Feb 28, 2022
Simple streamlit app to demonstrate HERE Tour Planning

Table of Contents About the Project Built With Getting Started Prerequisites Installation Usage Roadmap Contributing License Acknowledgements About Th

Amol 8 Sep 5, 2022
Industrial knn-based anomaly detection for images. Visit streamlit link to check out the demo.

Industrial KNN-based Anomaly Detection ⭐ Now has streamlit support! ⭐ Run $ streamlit run streamlit_app.py This repo aims to reproduce the results of

aventau 102 Dec 26, 2022
Streamlit Tutorial (ex: stock price dashboard, cartoon-stylegan, vqgan-clip, stylemixing, styleclip, sefa)

Streamlit Tutorials Install pip install streamlit Run cd [directory] streamlit run app.py --server.address 0.0.0.0 --server.port [your port] # http:/

Jihye Back 30 Jan 6, 2023
Seeing if I can put together an interactive version of 3b1b's Manim in Streamlit

streamlit-manim Seeing if I can put together an interactive version of 3b1b's Manim in Streamlit Installation I had to install pango with sudo apt-get

Adrien Treuille 6 Aug 3, 2022
A Deep learning based streamlit web app which can tell with which bollywood celebrity your face resembles.

Project Name: Which Bollywood Celebrity You look like A Deep learning based streamlit web app which can tell with which bollywood celebrity your face

BAPPY AHMED 20 Dec 28, 2021
In this project I played with mlflow, streamlit and fastapi to create a training and prediction app on digits

Fastapi + MLflow + streamlit Setup env. I hope I covered all. pip install -r requirements.txt Start app Go in the root dir and run these Streamlit str

null 76 Nov 23, 2022
Using Streamlit to host a multi-page tool with model specs and classification metrics, while also accepting user input values for prediction.

Predicitng_viability Using Streamlit to host a multi-page tool with model specs and classification metrics, while also accepting user input values for

Gopalika Sharma 1 Nov 8, 2021
Keywords : Streamlit, BertTokenizer, BertForMaskedLM, Pytorch

Next Word Prediction Keywords : Streamlit, BertTokenizer, BertForMaskedLM, Pytorch ?? Project Demo ✔ Application is hosted on Streamlit. You can see t

Vivek7 3 Aug 26, 2022
Playing around with FastAPI and streamlit to create a YoloV5 object detector

FastAPI-Streamlit-based-YoloV5-detector Playing around with FastAPI and streamlit to create a YoloV5 object detector It turns out that a User Interfac

null 2 Jan 20, 2022