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

How do I use valueFormatter? #100

Closed cozad-gurobi closed 2 years ago

cozad-gurobi commented 2 years ago

I am trying to create a large table with various customer number formatting (scientific notation, percentages, fixed decimal, etc.). I think I need to use the valueFormatter column property to do this.

I have been able to format fixed decimals using gb.configure_column("Number", type=["numericColumn","numberColumnFilter","customNumericFormat"], precision=5). However, I am still unable to see how to do this for formats like percentage and scientific notation.

I tried using the valueFormatter as shown in these examples, but I cannot seem to implement it properly. When I run the following code, I get a MarshallComponentException error:

Code example:

import pandas as pd
import streamlit as st
from st_aggrid import AgGrid
from st_aggrid.grid_options_builder import GridOptionsBuilder

data = [
    ['A', 0.00377603156157059], 
    ['B', 0.00381435124967479], 
    ['C', 0.00395809687885944], 
    ['D', 0.00818682681728073], 
    ]

df = pd.DataFrame(data, columns=['Row', 'Number'])

gb = GridOptionsBuilder.from_dataframe(df)

def my_valueFormatter(params):
    # Return a string formatted as a 2 decimal percentage
    return '{:.2%}'.format(params.value)

# Format my numbers.  I tried following the example here: https://www.ag-grid.com/javascript-data-grid/value-formatters/
gb.configure_column("Number", valueFormatter=my_valueFormatter) # Runs fine with this line commented out
gridOptions = gb.build()

AgGrid(df, 
        gridOptions=gridOptions,
        enable_enterprise_modules=True, 
        allow_unsafe_jscode=True, 
    ) 

Error I get when I run MarshallComponentException: ("Could not convert component args to JSON. If you're using custom JsCode objects on gridOptions, ensure that allow_unsafe_jscode is True.", TypeError('Object of type function is not JSON serializable'))

I would love help figuring out how to use valueFormatter in streamlit-aggrid. Failing that, if anyone has ideas on how to do scientific notation and percentage formatting, that would be a huge help.

cozad-gurobi commented 2 years ago

Aha! I figured out my solution based on #19

I need to replace my_valueFormatter with

my_valueFormatter = JsCode("""
        function(params) {
            x = JSON.parse(params.value);
            x = x*100;
            return  x.toFixed(2) + "%";
        }
        """)