Dash-ag-grid Value Formatting based on nulls/nans

I am trying to display distances in dash-ag-grid with Value Formatting using a suffix of miles. I want it to return “” when np.nan instead of “null miles”. Is there a way to achieve this?

Currently, i am using:
"valueFormatter": {"function": "params.value + ' miles'"}
which ends up returning:

image

Hello @uns123,

Typically, the best way is to do something like this:

{“function”:”params.value ? params.value + “ miles” : “”}

In JS, before the ? is evaluated for its truth. Params.value is testing that it exists and has a value in there. If false, this test goes to returning after the : , if true, it returns from before the :

3 Likes

I’d like to piggy back off this post and I can certainly make a new thread…

If I have a python array of floats with some nulls, how can I format numbers and keep nulls as blank?
There seems to be js that converts blank to 0 which is not desired.

I tried custom-functions-value-formatters, different null checks, different format properties like ‘missing’ but to no avail.
Any help would be appreciated.

Hi @usern23 and welcome to the Dash community.

The solution is similar to what @jinnyzor posted above. In this case to replace missing values with blanks, the function would look like:

{"function": "params.value? params.value : '' "}

Here is a complete minimal example

import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

data = {
    "item": ["A", "B", "C", "D"],
    "price": [1154.99, 268.65, 100.00, None],
}
df = pd.DataFrame(data)

columnDefs = [
    {"field": "item"},
    {
        "field": "price",
        "type": "rightAligned",
        "valueFormatter": {"function": "params.value? params.value : '' "},
    },
]


grid = dag.AgGrid(
    columnDefs=columnDefs,
    rowData=df.to_dict("records"),
)


app = Dash(__name__)

app.layout = html.Div(grid,style={"margin": 20})


if __name__ == "__main__":
    app.run(debug=True)

2 Likes