Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: support format_mapping for dataframe as table (#7745)

Holden X0c2d6d7fd1d2
diff --git a/docs/guides/working_with_data/dataframes.md b/docs/guides/working_with_data/dataframes.md
index 5d5552e51c..f625f0a037 100644
--- a/docs/guides/working_with_data/dataframes.md
+++ b/docs/guides/working_with_data/dataframes.md
@@ -223,6 +223,32 @@ def __():
///
+### Formatting values
+
+Use `format_mapping` to format values for display in the dataframe UI. This
+affects how values appear in the table but does not change the underlying
+data returned by `.value` or downloads.
+
+```python
+import marimo as mo
+import pandas as pd
+
+df = pd.DataFrame(
+ {"person": ["Alice", "Bob"], "age": [20, 30], "height_cm": [165.2, 180.4]}
+)
+
+def format_height(value: float) -> str:
+ return f"{value:.1f} cm"
+
+mo.ui.dataframe(
+ df,
+ format_mapping={
+ "age": "{:d} years".format,
+ "height_cm": format_height,
+ },
+)
+```
+
### Custom filters
Create custom filters with marimo UI elements, like sliders and dropdowns.
diff --git a/examples/ui/dataframe.py b/examples/ui/dataframe.py
index 4711483348..de4f1462b6 100644
--- a/examples/ui/dataframe.py
+++ b/examples/ui/dataframe.py
@@ -33,7 +33,17 @@ def _(mo):
@app.cell
def _(data, lazy_button, mo):
- dataframe_transformer = mo.ui.dataframe(data.iris(), lazy=lazy_button.value)
+ def format_length(value: float) -> str:
+ return f"{value:.1f} cm"
+
+ dataframe_transformer = mo.ui.dataframe(
+ data.iris(),
+ lazy=lazy_button.value,
+ format_mapping={
+ "sepal_length": format_length,
+ "sepal_width": "{:.1f}".format,
+ },
+ )
dataframe_transformer
return (dataframe_transformer,)
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 2739150ae2..853941f3b1 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -30,6 +30,7 @@ from marimo._plugins.ui._impl.table import (
SortArgs,
TableSearchError,
)
+from marimo._plugins.ui._impl.tables.format import FormatMapping
from marimo._plugins.ui._impl.tables.table_manager import (
FieldTypes,
TableManager,
@@ -110,6 +111,8 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
dataframes via Ibis.
show_download (bool, optional): Whether to show the download button.
Defaults to True.
+ format_mapping (Optional[Dict[str, Union[str, Callable[..., Any]]]], optional): A mapping from
+ column names to formatting strings or functions.
download_csv_encoding (str, optional): Encoding used when downloading CSV.
Defaults to "utf-8". Set to "utf-8-sig" to include BOM for Excel.
download_json_ensure_ascii (bool, optional): Whether to escape non-ASCII characters
@@ -130,6 +133,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
limit: Optional[int] = None,
show_download: bool = True,
*,
+ format_mapping: Optional[FormatMapping] = None,
download_csv_encoding: str = "utf-8",
download_json_ensure_ascii: bool = True,
lazy: Optional[bool] = None,
@@ -163,6 +167,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
self._download_json_ensure_ascii = download_json_ensure_ascii
self._handler = handler
self._manager = self._get_cached_table_manager(df, self._limit)
+ self._format_mapping = format_mapping
self._transform_container = TransformsContainer(nw_df, handler)
self._error: Optional[str] = None
self._last_transforms = Transformations([])
@@ -304,7 +309,9 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
# Save the manager to be used for selection
try:
- data = result.take(args.page_size, offset).to_json_str()
+ data = result.take(args.page_size, offset).to_json_str(
+ self._format_mapping
+ )
except BaseException as e:
# Catch and re-raise the error as a non-BaseException
# to avoid crashing the kernel
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
index 8b6f7920bd..e5c9e3ff06 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -173,6 +173,27 @@ class TestDataframes:
assert search_result.data == result.url
assert type(subject.value) is type(df)
+ @staticmethod
+ @pytest.mark.parametrize(
+ "df",
+ create_dataframes(
+ {"A": [1, 2], "B": ["a", "b"]},
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
+ ),
+ )
+ def test_dataframe_format_mapping(df: IntoDataFrame) -> None:
+ def format_value(value: int) -> str:
+ return f"val-{value}"
+
+ subject = ui.dataframe(df, format_mapping={"A": format_value})
+
+ search_result = subject._search(
+ SearchTableArgs(page_size=2, page_number=0)
+ )
+ data = json.loads(search_result.data)
+ assert {row["A"] for row in data} == {"val-1", "val-2"}
+ assert type(subject.value) is type(df)
+
@staticmethod
@pytest.mark.parametrize(
"df",