Git Product home page Git Product logo

streamlit-aggrid's People

Contributors

0xrushi avatar arky avatar arogozhnikov avatar broccoliboy avatar bwest2397 avatar colinmarsch avatar dectoplate avatar ghilesmeddour avatar hderek22 avatar jasonpmcculloch avatar kavehbc avatar kjakaitis avatar msabramo avatar pablocfonseca avatar randomseed42 avatar rensdimmendaal avatar sahajre avatar sfc-gh-amiribel avatar sfc-gh-pkommini avatar thunderbug1 avatar yoh1496 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

streamlit-aggrid's Issues

Data Type 'string' not understood error while returning aggrid Dataframe

Hi Pablo,

We've encountered an error using v 0.1.5 in which whenever the user edits the aggrid displayed grid, it returns "Data Type 'string' not understood" error. We've looked into the source code and realized that it needs a slight correction in L169 in init.py (referenced below). We've changed the line in our local source code to the line below and its resolved the issue.

We are kindly requesting the new changes so it doesn't error out on our users. Thank you so much!! Your package has been extremely useful for us.

Best,
Arshdeep and her teammate (Murat)

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.

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>

Cell Editing Support

How can we support 'cellEditor' and 'cellEditorParams' in grid options--this would extend the functionality of this package leaps and bounds.

Display cannot be set to false

Once a strealit aggrid component is displayed, and in case another aggrid needs to be displayed and the earlier one needs to be undiplayed it does not happen. I tried it with st.experimental_reload() or displaying a second aggrid with different key.

How to use custom cell renderers?

I am using the staggrid component and want to embed buttons which then open up a window to show some details about the row, something like this

For this to work I would need to inject a custom cell renderer (= js class) it into the existing staggrid component to be able to use it. Does anybody know how this could be done?

I’m not exactly a frontend developer, maybe it could also be a general javascript file that’s sort of globally defined for the streamlit website. I just need AgGrid to be able to see it.

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

.gitignore to remove build folder + eggs

Great job on this @PablocFonseca, pretty sure this will help a lot of users!

I forked your project and saw you were also versioning the build and Python egg-info. It makes it harder to check for code changes when working so I'd recommend copying Streamlit's gitignore and force removing the build + egg_info folders, what do you think ?

Cheers,
Fanilo

Format numbers with comma separating thousands

I'd like to display large numbers with comma separating thousands.

At first I assumed I could get this done with the Custom styling injecting JsCode on components front end.

I have this for example:
image
and I'd like to display like this to improve readability
image

here is what I tried but it's not producing any results

cellstyle_jscode = JsCode("""
valueFormatter(params) {
        return params.toString().split( /(?=(?:\d{3})+(?:\.|$))/g ).join( "," ),
};
""")

gb2.configure_column("Value", cellStyle=cellstyle_jscode)

gridOptions = gb2.build()

Any Idea on how I could get this to work?
I looked there to get the number formating in JavaScript

multiple jscode cellstyles

Hi,

First of all, thanks a lot for creating this package, it is amazing!

One question i have, is how i could apply multiple styles to the dataframe.
For example, this is the code to format negative numbers red and positive numbers green:

cellsytle_jscode = JsCode(
    """
function(params) {
    if (params.value < 0) {
        return {
            'color': 'white',
            'backgroundColor': 'darkred'
        }
    } else {
        return {
            'color': 'white',
            'backgroundColor': 'green'
        }
    }
};


"""
)

I would like to add another style to this column, where I want to show a dollar sign before the numbers.
Online I have found the following code:

function currencyFormatter(params) {
  return '£' + formatNumber(params.value);
}

How could I add that to streamlit-aggrid as well?

Thanks in advance!

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!

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)

Filter Setup

Hi guys,
your implementation of ag grid for streamlit is awesome. I'm loving it.
I wonder if there is any chance that i can get the filter setup, the user has currently selected?
I would love to save filter presets.
Greeting Pascapone

General Question: plugging in custom components

Awesome library @PablocFonseca! A quick question for you:

My firm has an enterprise license for AGGrid, but we also have a number of custom "wrappers" around the library in order to modify the look/feel of components. If we wanted to plug these into what you have built here what would be the path forward to do so? Really appreciate your time.

(Full disclosure: I am not a frontend dev by any stretch of the imagination so this is uncharted waters for me)

`gridOptions` dict example

First, thank you for this much needed component!

Please, consider the MWE below. I cannot figure out the syntax to pass the list of options directly to gridOptions, could you provide an example?

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, gridOptions= {'configure_selection':{'selection_mode':'multiple', 'use_checkbox':True}}) 

CVE's in npm package immer

The package-lock.json contains the following transitive npm dependency:
"immer": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/immer/-/immer-8.0.1.tgz",
"integrity": "sha512-aqXhGP7//Gui2+UrEtvxZxSquQVXTpZ7KDxfCcKAF3Vysvw0CViVaW9RZ1j1xlIYqaaaipBoqdqeibkc18PNvA=="
},
This package contains the CVE's below. Could you please explicitly bump the immer package to "^9.06" (as in the streamlit main package)?
https://nvd.nist.gov/vuln/detail/CVE-2021-23436
https://nvd.nist.gov/vuln/detail/CVE-2021-3757

Show dataframe index in grid

Currently dataframes are displayed without their index columns.

Suggested solution:
Add another for loop before this one:

for col_name, col_type in zip(dataframe.columns, dataframe.dtypes):

With the following code:

index = dataframe.index
if isinstance(index, MultiIndex):
    for level in index:
        gb.configure_column(field=level.name, type=type_mapper.get(level.dtype.kind, []))
else:
    gb.configure_column(field=index.name, type=type_mapper.get(index.dtype.kind, []))

Note that index name could be None, I dunno how it handles such a case.
It might be convenient to wrap this piece of code in some kind of "display index column" configuration (through grid options?) that lets the user decide whether to display the index or not.

And... it seems the above code indeed adds an index column, but doesn't populate it.

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!

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)

Update AgGrid to 25.1.0

There's a bug in 24.1.0 we're hitting related to sorting (AG-4861) that's been fixed in 25.1.0, would it be possible for you to update?

thanks!

Demo app seems to be broken

Summary

This is what I see when I visit the demo app:

image

Browser / OS Information

  • Browser: Version 94.0.4606.81 (Official Build) (x86_64)
  • OS: macOS 11.6 (20G165)
  • Hardware: MacBook Pro 8-Core Intel Core i9

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.

problem to aggregate columns

First of all, I would like to congratulate you for such an amazing component.

I would like to address that I am experiencing what seems a bug.

As you can see in the video, when I try to add a column to aggregate its value, nothing happen. Due to that, if I delete by mistake a calculation of one column, the only possible way to add it again is to refresh the page.
aggrid-streamlit

Another question that I would like to ask is if there is possible to download the resulting dataframe, i.e, let say that I filter a dataframe by a column, to download or export this resulting dataframe filtered. I look for it in the internet by I didn't find this functionality in the component.

Again thank you for such an amazing component

edited cell does not render anymore

Hi,
This is very great thank you!
I Noticed since yesterday update that the table does not render when the cell is edited (see screencast)
The value does seem to get transfered though but it does not appear in the table.
Could this be an issue with the formating function?
Thanks!

streamlit-example-2021-01-04-18-01-12.MOV

Periods in columns names make all entries in that column blank

There's a bug that occurs when a period is present in the name of a column entered into AgGrid, all values in that column are displayed as empty. It can be visually worked around by replacing any periods in column names with the "one dot leader" character ("․", U+2024, or "\u2024" in Python), but that's an imperfect solution as the column names need to be restored in the returned dataframe.

Demo code snippet:

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

st.write('### No periods in column names')
df_no_dots = pd.DataFrame({'field_1':['a','b','c','d'], 'field_2':[1,2,3,4]})
AgGrid(df_no_dots)

st.write('---\n### One columns name with period, one without')
df_half_dots = pd.DataFrame({'field.1':['a','b','c','d'], 'field_2':[1,2,3,4]})
AgGrid(df_half_dots)

st.write('---\n### Both columns names with periods')
df_both_dots = pd.DataFrame({'field.1':['a','b','c','d'], 'field.2':[1,2,3,4]})
AgGrid(df_both_dots)

st.write("The same data, but with the table set as editable")
return_df = AgGrid(df_both_dots, editable=True)

st.write("The output of this displayed using st.dataframe demonstrates that the data is not being deleted, it just isn't being displayed")
st.dataframe(return_df['data'])

st.write('---\n### Workaround by replacing periods in column names with similar "one dot leader" character ("\u2024", U+2024)')
df_dots_workaround = df_both_dots.rename(columns=lambda col : col.replace('.','\u2024'))
AgGrid(df_dots_workaround)

Screenshots of the examples in the code snippet:

image

image

image

image

"Open in Streamlit" Examples do not seem to work

Hi there @PablocFonseca!

I am a big fan of this streamlit component and am currently learning how to use it as I build out an application for internal company use. It is a huge improvement over the standard dataframe rendering offered by streamlit. Thank you!

During my learning process, I am referring to your examples and I noticed that they do not seem to run for some reason. I am guessing it's a streamlit version issue or something. The following happens both on my own machine, when I run your examples directly with streamlit v0.89, and when I click the "Run in Streamlit" badge on your README.md:

When loading example.py, the page loads, I see it rendered for a split second, then the page goes blank but I still see the streamlit logo in the bottom right-hand corner:
image

Your example.py file runs a multi-page app that references other files like main_example.py, etc. Now, when I attempt to run some of these other pages directly, I can. e.g. fixed_key_example.py. However, I cannot do this to run main_example.py, the page goes blank again.

I am running the following:

  • Windows 10
  • Firefox 93.0 (same behaviour observed in Chrome)

Have been learning a lot from just reading the code in your examples but would love to be able to interact with them.

If you think you are able to fix this bug in your examples, it would be great for learning more about the subtleties of working with this component.

Many thanks!

ModuleNotFoundError: No module named 'st_aggrid'

Tried the example, does not work. Returned a ModuleNotFoundError: No module named 'st_aggrid'.
(new python env, with pip install streamlit and streamlit-aggrid)

image

▶ pip list             
Package             Version
------------------- ---------
altair              4.1.0
argon2-cffi         20.1.0
astor               0.8.1
async-generator     1.10
attrs               20.3.0
backcall            0.2.0
base58              2.1.0
bleach              3.3.0
blinker             1.4
cachetools          4.2.1
certifi             2020.12.5
cffi                1.14.5
chardet             4.0.0
click               7.1.2
decorator           5.0.6
defusedxml          0.7.1
entrypoints         0.3
Faker               8.0.0
gitdb               4.0.7
GitPython           3.1.14
idna                2.10
ipykernel           5.5.3
ipython             7.22.0
ipython-genutils    0.2.0
ipywidgets          7.6.3
jedi                0.18.0
Jinja2              2.11.3
jsonschema          3.2.0
jupyter-client      6.2.0
jupyter-core        4.7.1
jupyterlab-pygments 0.1.2
jupyterlab-widgets  1.0.0
MarkupSafe          1.1.1
mistune             0.8.4
nbclient            0.5.3
nbconvert           6.0.7
nbformat            5.1.3
nest-asyncio        1.5.1
notebook            6.3.0
numpy               1.20.2
packaging           20.9
pandas              1.2.4
pandocfilters       1.4.3
parso               0.8.2
pexpect             4.8.0
pickleshare         0.7.5
Pillow              8.2.0
pip                 20.1
prometheus-client   0.10.1
prompt-toolkit      3.0.18
protobuf            3.15.8
ptyprocess          0.7.0
pyarrow             3.0.0
pycparser           2.20
pydeck              0.6.2
Pygments            2.8.1
pyparsing           2.4.7
pyrsistent          0.17.3
python-dateutil     2.8.1
pytz                2021.1
pyzmq               22.0.3
requests            2.25.1
Send2Trash          1.5.0
setuptools          46.1.3
simplejson          3.17.2
six                 1.15.0
smmap               4.0.0
streamlit           0.80.0
streamlit-aggrid    0.1.9
terminado           0.9.4
testpath            0.4.4
text-unidecode      1.3
toml                0.10.2
toolz               0.11.1
tornado             6.1
traitlets           5.0.5
tzlocal             2.1
urllib3             1.26.4
validators          0.18.2
watchdog            2.0.2
wcwidth             0.2.5
webencodings        0.5.1
wheel               0.34.2
widgetsnbextension  3.5.

Any idea ?

When the number of rows in table is small and `reload_data=True`, the selection doesn't show up in UI

When the number of rows in the table is small and reload_data=True, the selection doesn't show up

Minimal example to reproduce:

import streamlit as st
from st_aggrid import GridOptionsBuilder, AgGrid
import pandas as pd

csv_url = (
    "http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
)
df = pd.read_csv(csv_url, sep=";")
df = df.head(28)  # HERE!!! when set to 29, it's working

st.title("Not showing selection example")

gb1 = GridOptionsBuilder.from_dataframe(df)
gb1.configure_selection(selection_mode="multiple", use_checkbox=True)
gridOptions = gb1.build()
response = AgGrid(
    df,
    gridOptions=gridOptions,
    width="100%",
    update_mode="SELECTION_CHANGED",
    reload_data=True,
    key='example',
)

print(response['selected_rows'])

The row that is selected is printed but you can't see it in the UI

selected_rows in grid_response sometimes empty

Sometimes the selected_rows entry in grid_response is empty despite having multiple rows selected,
I can't really reproduce this reliably but it happens like 50% of the time in my application, for other users almost every time but not always.
Can it be that there is some kind of race condition somewhere in the feedback stream?

[QUESTION] How to create tooltip on a column?

It would be good to know how to get rid of "..." and to show a full string instead.
Screenshot 2021-02-10 at 09 21 49

One possible approach is the following one.
When the user hovers on an item, a tooltip is displayed.

It would be good to know how to configure the tooltip. Thank you in advance for any info!

Banded rows

Hi Pablo,

Thank you for implementing a great component.

I read the documentation and examples, and I could not find a way to make banded rows by alternating in colors. (background color of even rows is white and odd are gray, for instance)

Any help or comment would be greatly appreciated.

Thanks,
Bader

Improvement request: Refreshing without disappearing for a moment

Currently, every time the streamlit-aggrid component is refreshed/redrawn it disappears for a short moment. This experience for the user can be a bit confusing.

A potential improvement would be for the table to refresh without disappearing (this is already the behavior of Streamlit's native widgets).

In any case, thanks again for developing this component @PablocFonseca

Pandas FutureWarning

Hey 👋 Thanks for the great package!

I'm encountering the following warning:

/Users/.../.venv/lib/python3.9/site-packages/st_aggrid/__init__.py:253: FutureWarning: Passing a dict as an indexer is deprecated and will raise in a future version. Use a list instead.
  frame.loc[:,text_columns]  = frame.loc[:,text_columns].astype(str)

I'm using the following versions:

  • st_aggrid 0.2.3
  • pandas 1.4.0
  • streamlit 1.4.0

I believe the solution would be to use text_columns.keys() instead of text_columns. And to make similar changes for the other column types in st_aggrid/__init__.py

Happy to submit a PR with these changes if you like.

Custom row agregation function

Hello, first of all thank you very much for this lib that I found so useful.

I was wondering if it was possible to implement in the configure_column of the option_builder a custom aggFunc in python. I acutally want to recompute the information the grid is showing for each granularity and not just do a sum or an average. I saw it was possible to do it in JavaScript but I wanted to know if there was an easier way to implement a python function to do Multi-Column Aggregation.

Thank you again for your amazing work ! Hope my question was clear.

Have a nice day

pyarrow.lib.ArrowInvalid: "Could not convert '5' with type str: tried to convert to int"

I'm using essentially the same code that is in the "main example" provided in this repository for a table with numeric values. When I edit the numbers in the Streamlit page (for example change one of the cells to 5) I get the error below:

pyarrow.lib.ArrowInvalid: ("Could not convert '5' with type str: tried to convert to int", 'Conversion failed for column [name of column] with type object')

I checked the data frame the table is initialized with and the columns are all type int.

Grid State

How to persist grid state after reload. I mean if the user interacts with the grid and changes column order, sorting, grouping, etc. How to persist these changes on reload. Is there a callback to handle those events?

Have streamlit-aggrid play nicely with themes

Hi @PablocFonseca, greetings from the Streamlit team!

This is a bit of a funny issue (at least at the time that I'm writing this) since the request in it isn't possible in the current version of streamlit. We wanted to give you an early heads up since the streamlit-aggrid component is one with quite a bit of community interest.

We're looking to launch a themes feature in the near future, which will add support for a native dark mode as well as allow developers to define their own custom themes. Theming will interact with components by both passing a theme JSON object defining the theme to the component as well as injecting css into the iframe the component lives in.

Since streamlit-aggrid is so popular, we'd be thrilled to have it as one of the first components to work nicely with themes, and thus I'm filing this issue early! I'll bump this issue once theming has been officially released, but if you happen to want to play around with it before then, I think I should be able to arrange getting a wheel-file containing a prototype to you 🙂

Feedback

Hi @PablocFonseca,

this component is really awesome and I'd like to thank you! 🎈

So here I have some questions, ideas and suggestion to make the component even more awesome:

  1. It would be super nice, if we could reduce the code required to get the whole thing up and running with all features.
    1.1. So - i wanted to ask if it is possible to include the sidebar out of the box, if someone does this AGrid() its automatically there and instead of configrung all over again, just give the option to not show it e.g. Agrid(disable=["selection_mode"]).
    Cauz i guess most people wants to have it working out of the box.
    st.sidebar.subheader("St-AgGrid example options")
    sample_size = st.sidebar.number_input("rows", min_value=10, value=3000)
    return_mode = st.sidebar.selectbox ("Return Mode", list (DataReturnMode.__members__), index=1)
    return_mode_value = DataReturnMode.__members__[return_mode]

    update_mode = st.sidebar.selectbox("Update Mode", list (GridUpdateMode.__members__), index=6)
    update_mode_value = GridUpdateMode.__members__[update_mode]
    enable_selection = st.sidebar.checkbox ("Enable row selection", value=True)

    if enable_selection:
        st.sidebar.subheader ("Selection options")
        selection_mode = st.sidebar.radio("Selection Mode", ['single', 'multiple'])

        use_checkbox = st.sidebar.checkbox ("Use check box for selection")
        if use_checkbox:
            groupSelectsChildren = st.sidebar.checkbox ("Group checkbox select children", value=True)
            groupSelectsFiltered = st.sidebar.checkbox ("Group checkbox includes filtered", value=True)

        if ((selection_mode == 'multiple') & (not use_checkbox)):
            rowMultiSelectWithClick = st.sidebar.checkbox ("Multiselect with click (instead of holding CTRL)",
                                                           value=False)
            if not rowMultiSelectWithClick:
                suppressRowDeselection = st.sidebar.checkbox ("Suppress deselection (while holding CTRL)", value=False)
            else:
                suppressRowDeselection = False
        st.sidebar.text("___")

    enable_pagination = st.sidebar.checkbox ("Enable pagination", value=False)
    if enable_pagination:
        st.sidebar.subheader("Pagination options")
        paginationAutoSize = st.sidebar.checkbox("Auto pagination size", value=True)
        if not paginationAutoSize:
            paginationPageSize = st.sidebar.number_input("Page size", value=5, min_value=0, max_value=sample_size)
        st.sidebar.markdown("___")

1.2. also things like this are to complicated and just blow the code in my view:

cellsytle_jscode = JsCode("""
function(params) {
    if (params.value == 'A') {
        return {
            'color': 'white',
            'backgroundColor': 'darkred'
        }
    } else {
        return {
            'color': 'black',
            'backgroundColor': 'white'
        }
    }
};
""")
gb.configure_column("group", cellStyle=cellsytle_jscode)

I was not sure if i had to include it so i did, but would it still work without it? Also it's not really pythonic. maybe there is a way to include it in Agrid()?

Just reducing the needed code to this part and maybe the cols (but also could be intered from df?) would be best:

    agrid = AgGrid(
        df,
        gridOptions=gridOptions,
        width='100%',
        data_return_mode=return_mode_value,
        update_mode=update_mode_value,
        allow_unsafe_jscode=True,
    )
    df = agrid['data']
    selected = agrid['selected_rows']
  1. My next question is regarding the filtering options, could I have a st.sidebar.multiselect() that shows all the filtering options choosen from the agrid?

  2. The last question is regarding updating the data as it happens if I select some datapoints/rows from agrid.
    Is there a way to update the data by injecting a new dataframe at a later point in time? For example I create
    the agrid somehere at the top, at the middle i created/filtered the returned datframe and want to update the agrid
    with the df created? I tried agrid["data"] = df but didnt work. Any ideas?

Thank you so much again for this awesome component!
Hope my ideas help to make it even better.

Best regards
Chris

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.