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.

Fix #775: Ability to style / format mo.ui.table() (#1881)

H. Eugene6c85c4d2201c
diff --git a/frontend/src/components/data-table/__test__/column_formatting.test.ts b/frontend/src/components/data-table/__test__/column_formatting.test.ts
new file mode 100644
index 0000000000..b8b2b548db
--- /dev/null
+++ b/frontend/src/components/data-table/__test__/column_formatting.test.ts
@@ -0,0 +1,60 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { applyFormat } from "../column-formatting/feature";
+import { prettyNumber, prettyScientificNumber } from "@/utils/numbers";
+
+describe("applyFormat", () => {
+ it("should return an empty string for null, undefined, or empty string values", () => {
+ expect(applyFormat(null, "Date", "date")).toBe("");
+ expect(applyFormat(undefined, "Date", "date")).toBe("");
+ expect(applyFormat("", "Date", "date")).toBe("");
+ });
+
+ describe("date formatting", () => {
+ it("should format date values correctly", () => {
+ const date = "2023-10-01T12:00:00Z";
+ expect(applyFormat(date, "Date", "date")).toBe("10/1/2023");
+ expect(applyFormat(date, "Datetime", "date")).toBe(
+ "2023-10-01T12:00:00.000Z",
+ );
+ });
+ });
+
+ describe("number formatting", () => {
+ it("should format number values correctly", () => {
+ const number = "1234.567";
+ expect(applyFormat(number, "Auto", "number")).toBe(
+ prettyNumber(1234.567),
+ );
+ expect(applyFormat(number, "Percent", "number")).toBe("123456.70%");
+ expect(applyFormat(number, "Scientific", "number")).toBe(
+ prettyScientificNumber(1234.567),
+ );
+ expect(applyFormat(number, "Int", "number")).toBe("1235");
+ });
+ });
+
+ describe("string formatting", () => {
+ it("should format string values correctly", () => {
+ const str = "hello world";
+ expect(applyFormat(str, "Uppercase", "string")).toBe("HELLO WORLD");
+ expect(applyFormat(str, "Lowercase", "string")).toBe("hello world");
+ expect(applyFormat(str, "Capitalize", "string")).toBe("Hello world");
+ expect(applyFormat(str, "Title", "string")).toBe("Hello World");
+ });
+ });
+
+ describe("boolean formatting", () => {
+ it("should format boolean values correctly", () => {
+ expect(applyFormat(true, "Yes/No", "boolean")).toBe("Yes");
+ expect(applyFormat(false, "Yes/No", "boolean")).toBe("No");
+ expect(applyFormat(true, "On/Off", "boolean")).toBe("On");
+ expect(applyFormat(false, "On/Off", "boolean")).toBe("Off");
+ });
+ });
+
+ it("should return the original value for unknown data types or formats", () => {
+ expect(applyFormat("some value", "Auto", "unknown")).toBe("some value");
+ expect(applyFormat(123, "Auto", "unknown")).toBe(123);
+ });
+});
diff --git a/frontend/src/components/data-table/column-formatting/feature.ts b/frontend/src/components/data-table/column-formatting/feature.ts
new file mode 100644
index 0000000000..35a6502b9f
--- /dev/null
+++ b/frontend/src/components/data-table/column-formatting/feature.ts
@@ -0,0 +1,151 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import {
+ TableFeature,
+ RowData,
+ makeStateUpdater,
+ Table,
+ Column,
+ Updater,
+} from "@tanstack/react-table";
+import {
+ ColumnFormattingTableState,
+ ColumnFormattingOptions,
+ ColumnFormattingState,
+} from "./types";
+import { DataType } from "@/core/kernel/messages";
+import { type FormatOption } from "./types";
+import { prettyNumber, prettyScientificNumber } from "@/utils/numbers";
+
+export const ColumnFormattingFeature: TableFeature = {
+ // define the column formatting's initial state
+ getInitialState: (state): ColumnFormattingTableState => {
+ return {
+ columnFormatting: {},
+ ...state,
+ };
+ },
+
+ // define the new column formatting's default options
+ getDefaultOptions: <TData extends RowData>(
+ table: Table<TData>,
+ ): ColumnFormattingOptions => {
+ return {
+ enableColumnFormatting: true,
+ onColumnFormattingChange: makeStateUpdater("columnFormatting", table),
+ } as ColumnFormattingOptions;
+ },
+
+ createColumn: <TData extends RowData>(
+ column: Column<TData>,
+ table: Table<TData>,
+ ) => {
+ column.getColumnFormatting = () => {
+ return table.getState().columnFormatting[column.id];
+ };
+
+ column.getCanFormat = () => {
+ return (
+ (table.options.enableColumnFormatting &&
+ column.columnDef.meta?.dataType !== "unknown" &&
+ column.columnDef.meta?.dataType !== undefined) ??
+ false
+ );
+ };
+
+ column.setColumnFormatting = (value) => {
+ const safeUpdater: Updater<ColumnFormattingState> = (old) => {
+ return {
+ ...old,
+ [column.id]: value,
+ };
+ };
+ table.options.onColumnFormattingChange?.(safeUpdater);
+ };
+
+ // apply column formatting
+ column.applyColumnFormatting = (value) => {
+ const dataType = column.columnDef.meta?.dataType;
+ const format = column.getColumnFormatting?.();
+ if (format) {
+ return applyFormat(value, format, dataType);
+ }
+ return value;
+ };
+ },
+};
+
+// Apply formatting to a value given a format and data type
+export const applyFormat = (
+ value: unknown,
+ format: FormatOption,
+ dataType: DataType | undefined,
+) => {
+ // If the value is null, return an empty string
+ if (value === null || value === undefined || value === "") {
+ return "";
+ }
+ // Handle date, number, string and boolean formatting
+ switch (dataType) {
+ case "date": {
+ const date = new Date(value as string);
+ switch (format) {
+ case "Date":
+ return date.toLocaleDateString("en-US");
+ case "Datetime":
+ return date.toISOString();
+ case "Time":
+ return date.toTimeString();
+ default:
+ return value;
+ }
+ }
+ case "number": {
+ const num = Number.parseFloat(value as string);
+ switch (format) {
+ case "Auto":
+ return prettyNumber(num);
+ case "Percent":
+ return `${(num * 100).toFixed(2)}%`;
+ case "Scientific":
+ return prettyScientificNumber(num);
+ case "Int":
+ return num.toFixed(0);
+ default:
+ return value;
+ }
+ }
+ case "string":
+ switch (format) {
+ case "Uppercase":
+ return (value as string).toUpperCase();
+ case "Lowercase":
+ return (value as string).toLowerCase();
+ case "Capitalize":
+ return (
+ (value as string).charAt(0).toUpperCase() +
+ (value as string).slice(1)
+ );
+ case "Title":
+ return (value as string)
+ .split(" ")
+ .map(
+ (word) =>
+ word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),
+ )
+ .join(" ");
+ default:
+ return value;
+ }
+ case "boolean":
+ switch (format) {
+ case "Yes/No":
+ return (value as boolean) ? "Yes" : "No";
+ case "On/Off":
+ return (value as boolean) ? "On" : "Off";
+ default:
+ return value;
+ }
+ default:
+ return value;
+ }
+};
diff --git a/frontend/src/components/data-table/column-formatting/types.ts b/frontend/src/components/data-table/column-formatting/types.ts
new file mode 100644
index 0000000000..52a16f4558
--- /dev/null
+++ b/frontend/src/components/data-table/column-formatting/types.ts
@@ -0,0 +1,51 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-empty-interface */
+import { DataType } from "@/core/kernel/messages";
+import { OnChangeFn, RowData } from "@tanstack/react-table";
+
+// define all format options
+export const formatOptions = {
+ date: ["Date", "Datetime", "Time"],
+ integer: [],
+ number: ["Auto", "Percent", "Scientific", "Int"],
+ string: ["Uppercase", "Lowercase", "Capitalize", "Title"],
+ boolean: ["Yes/No", "On/Off"],
+ unknown: [],
+} as const satisfies Record<DataType, string[]>;
+
+// define types for format options
+export type FormatOptions = (typeof formatOptions)[keyof typeof formatOptions];
+export type FormatOption = FormatOptions[number];
+
+// define types for column formatting's custom state
+export type ColumnFormattingState = Record<string, FormatOption | undefined>;
+export interface ColumnFormattingTableState {
+ columnFormatting: ColumnFormattingState;
+}
+
+// define types for column formatting's table options
+export interface ColumnFormattingOptions {
+ enableColumnFormatting?: boolean;
+ onColumnFormattingChange?: OnChangeFn<ColumnFormattingState>;
+}
+
+// define types for column formatting's table APIs
+export interface ColumnFormattingInstance {
+ setColumnFormatting: (value?: FormatOption) => void;
+ getColumnFormatting?: () => FormatOption | undefined;
+ getCanFormat?: () => boolean;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ applyColumnFormatting: (value: any) => any;
+}
+
+// Use declaration merging to add APIs and state types
+// to TanStack Table's existing types.
+declare module "@tanstack/react-table" {
+ //merge column formatting's state with the existing table state
+ interface TableState extends ColumnFormattingTableState {}
+ //merge column formatting's options with the existing table options
+ interface TableOptionsResolved<TData extends RowData>
+ extends ColumnFormattingOptions {}
+ //merge column formatting's instance APIs with the existing table instance APIs
+ interface Column<TData extends RowData> extends ColumnFormattingInstance {}
+}
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index 90a6234be8..74a5659c01 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -10,6 +10,7 @@ import {
MinusIcon,
SearchIcon,
WrapTextIcon,
+ Text,
AlignJustifyIcon,
} from "lucide-react";
@@ -31,6 +32,8 @@ import { NumberField } from "../ui/number-field";
import { Input } from "../ui/input";
import { ColumnFilterForType, Filter } from "./filters";
import { logNever } from "@/utils/assertNever";
+import { DataType } from "@/core/kernel/messages";
+import { formatOptions } from "./column-formatting/types";
interface DataTableColumnHeaderProps<TData, TValue>
extends React.HTMLAttributes<HTMLDivElement> {
@@ -79,8 +82,6 @@ export const DataTableColumnHeader = <TData, TValue>({
);
};
- const dtype = column.columnDef.meta?.dtype;
-
const renderColumnWrapping = () => {
if (!column.getCanWrap?.() || !column.getColumnWrapping) {
return null;
@@ -110,6 +111,44 @@ export const DataTableColumnHeader = <TData, TValue>({
);
};
+ const dtype: string | undefined = column.columnDef.meta?.dtype;
+ const dataType: DataType | undefined = column.columnDef.meta?.dataType;
+ const columnFormatOptions = dataType ? formatOptions[dataType] : [];
+
+ const renderFormatOptions = () => {
+ if (columnFormatOptions.length === 0 || !column.getCanFormat?.()) {
+ return null;
+ }
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Text className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
+ Format
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ {Boolean(column.getColumnFormatting?.()) && (
+ <DropdownMenuItem
+ key={"clear"}
+ onClick={() => column.setColumnFormatting(undefined)}
+ >
+ Clear
+ </DropdownMenuItem>
+ )}
+ {columnFormatOptions.map((option) => (
+ <DropdownMenuItem
+ key={option}
+ onClick={() => column.setColumnFormatting(option)}
+ >
+ {option}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ );
+ };
+
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild={true}>
@@ -157,6 +196,7 @@ export const DataTableColumnHeader = <TData, TValue>({
Copy column name
</DropdownMenuItem>
{renderColumnWrapping()}
+ {renderFormatOptions()}
<DropdownMenuItemFilter column={column} />
</DropdownMenuContent>
</DropdownMenu>
@@ -294,7 +334,9 @@ export const DropdownMenuItemFilter = <TData, TValue>({
const NumberRangeFilter = <TData, TValue>({
column,
-}: { column: Column<TData, TValue> }) => {
+}: {
+ column: Column<TData, TValue>;
+}) => {
const currentFilter = column.getFilterValue() as
| ColumnFilterForType<"number">
| undefined;
@@ -373,7 +415,9 @@ const NumberRangeFilter = <TData, TValue>({
const TextFilter = <TData, TValue>({
column,
-}: { column: Column<TData, TValue> }) => {
+}: {
+ column: Column<TData, TValue>;
+}) => {
const currentFilter = column.getFilterValue() as
| ColumnFilterForType<"text">
| undefined;
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index d40d7a9510..ecd451cbff 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -90,6 +90,7 @@ export function generateColumns<T>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (row as any)[info.key];
},
+
header: ({ column }) => {
// Row headers have no summaries
if (rowHeadersSet.has(info.key)) {
@@ -108,13 +109,20 @@ export function generateColumns<T>({
/>
);
},
- cell: ({ renderValue, getValue }) => {
+
+ cell: ({ column, renderValue, getValue }) => {
// Row headers are bold
if (rowHeadersSet.has(info.key)) {
return <b>{String(renderValue())}</b>;
}
const value = getValue();
+
+ const format = column.getColumnFormatting?.();
+ if (format) {
+ return column.applyColumnFormatting(value);
+ }
+
if (isPrimitiveOrNullish(value)) {
const rendered = renderValue();
if (rendered == null) {
@@ -133,6 +141,7 @@ export function generateColumns<T>({
rowHeader: rowHeadersSet.has(info.key),
filterType: getFilterTypeForFieldType(fieldTypes?.[info.key]?.[0]),
dtype: fieldTypes?.[info.key]?.[1],
+ dataType: fieldTypes?.[info.key]?.[0],
},
}),
);
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index a83018185b..e33f4cdcbb 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -34,6 +34,7 @@ import { Tooltip } from "../ui/tooltip";
import { Spinner } from "../icons/spinner";
import { FilterPills } from "./filter-pills";
import { ColumnWrappingFeature } from "./column-wrapping/feature";
+import { ColumnFormattingFeature } from "./column-formatting/feature";
interface DataTableProps<TData> extends Partial<DownloadActionProps> {
wrapperClassName?: string;
@@ -93,7 +94,7 @@ const DataTableInternal = <TData,>({
}, [pageSize, paginationState.pageSize]);
const table = useReactTable({
- _features: [ColumnWrappingFeature],
+ _features: [ColumnWrappingFeature, ColumnFormattingFeature],
data,
columns,
getCoreRowModel: getCoreRowModel(),
diff --git a/frontend/src/components/data-table/filters.ts b/frontend/src/components/data-table/filters.ts
index 5ecbd4274d..11fe585f9e 100644
--- a/frontend/src/components/data-table/filters.ts
+++ b/frontend/src/components/data-table/filters.ts
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { DataType } from "@/core/kernel/messages";
import { ConditionType } from "@/plugins/impl/data-frames/schema";
import { ColumnId } from "@/plugins/impl/data-frames/types";
import { assertNever } from "@/utils/assertNever";
@@ -11,6 +12,7 @@ declare module "@tanstack/react-table" {
type?: "primitive" | "mime";
rowHeader?: boolean;
dtype?: string;
+ dataType?: DataType;
filterType?: FilterType;
}
}
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index c809c45a68..12b3128c1e 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -134,6 +134,27 @@ class table(
)
```
+ Create a table with format mapping:
+
+ ```python
+ # format_mapping is a dict keyed by column names,
+ # with values as formatting functions or strings
+ def format_name(name):
+ return name.upper()
+
+
+ table = mo.ui.table(
+ data=[
+ {"first_name": "Michael", "last_name": "Scott", "age": 45},
+ {"first_name": "Dwight", "last_name": "Schrute", "age": 40},
+ ],
+ format_mapping={
+ "first_name": format_name, # Use callable to format first names
+ "age": "{:.1f}".format, # Use string format for age
+ },
+ label="Format Mapping",
+ )
+ ```
In each case, access the table data with `table.value`.
**Attributes.**
@@ -161,6 +182,8 @@ class table(
- `page_size`: the number of rows to show per page.
defaults to 10
- `show_column_summaries`: whether to show column summaries
+ - `format_mapping`: a mapping from column names to formatting strings
+ or functions
- `label`: text label for the element
- `on_change`: optional callback to run when this element's value changes
"""
@@ -181,6 +204,9 @@ class table(
selection: Optional[Literal["single", "multi"]] = "multi",
page_size: int = 10,
show_column_summaries: bool = True,
+ format_mapping: Optional[
+ Dict[str, Union[str, Callable[..., Any]]]
+ ] = None,
*,
label: str = "",
on_change: Optional[
@@ -246,12 +272,12 @@ class table(
label=label,
initial_value=[],
args={
- "data": self._filtered_manager.to_data(),
+ "data": self._filtered_manager.to_data(format_mapping),
"has-more": has_more,
"total-rows": total_rows,
"pagination": pagination,
"page-size": page_size,
- "field-types": field_types if field_types else None,
+ "field-types": field_types or None,
"selection": (
selection if self._manager.supports_selection() else None
),
@@ -296,6 +322,7 @@ class table(
def download_as(self, args: DownloadAsArgs) -> str:
# download selected rows if there are any, otherwise use all rows
+ # not apply formatting here, raw data is downloaded
manager = (
self._selected_manager
if self._selected_manager and self._has_any_selection
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 7b85931802..98b8217ae8 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -5,6 +5,7 @@ from typing import (
Any,
Dict,
List,
+ Optional,
Sequence,
Union,
cast,
@@ -14,6 +15,11 @@ from marimo._data.models import ColumnSummary
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.mime import MIME
from marimo._plugins.core.web_component import JSONType
+from marimo._plugins.ui._impl.tables.format import (
+ FormatMapping,
+ format_column,
+ format_row,
+)
from marimo._plugins.ui._impl.tables.pandas_table import (
PandasTableManagerFactory,
)
@@ -50,14 +56,37 @@ class DefaultTableManager(TableManager[JsonTableData]):
or DependencyManager.has_pyarrow()
)
+ def apply_formatting(self, format_mapping: FormatMapping) -> JsonTableData:
+ if isinstance(self.data, dict) and all(
+ isinstance(value, (list, tuple)) for value in self.data.values()
+ ):
+ return {
+ col: format_column(col, values, format_mapping) # type: ignore
+ for col, values in self.data.items()
+ }
+ if isinstance(self.data, (list, tuple)) and all(
+ isinstance(item, dict) for item in self.data
+ ):
+ return [
+ format_row(row, format_mapping) # type: ignore
+ for row in self.data
+ ]
+ return self.data
+
def supports_filters(self) -> bool:
return False
- def to_data(self) -> JSONType:
- return self._normalize_data(self.data)
+ def to_data(
+ self, format_mapping: Optional[FormatMapping] = None
+ ) -> JSONType:
+ return (
+ self._normalize_data(self.apply_formatting(format_mapping))
+ if format_mapping
+ else self._normalize_data(self.data)
+ )
- def to_csv(self) -> bytes:
- return self._as_table_manager().to_csv()
+ def to_csv(self, format_mapping: Optional[FormatMapping] = None) -> bytes:
+ return self._as_table_manager().to_csv(format_mapping)
def to_json(self) -> bytes:
return self._as_table_manager().to_json()
@@ -102,27 +131,18 @@ class DefaultTableManager(TableManager[JsonTableData]):
def search(self, query: str) -> DefaultTableManager:
query = query.lower()
if isinstance(self.data, dict):
- mask: List[bool] = []
- for row in range(self.get_num_rows() or 0):
- mask.append(
- any(
- query in str(self.data[key][row]).lower()
- for key in self.data.keys()
- )
+ mask: List[bool] = [
+ any(
+ query in str(self.data[key][row]).lower()
+ for key in self.data.keys()
)
+ for row in range(self.get_num_rows() or 0)
+ ]
results: JsonTableData = {
key: [value[i] for i, match in enumerate(mask) if match]
for key, value in self.data.items()
}
return DefaultTableManager(results)
- if isinstance(self.data, list):
- return DefaultTableManager(
- [
- row
- for row in self._normalize_data(self.data)
- if any(query in str(v).lower() for v in row.values())
- ]
- )
return DefaultTableManager(
[
row
@@ -167,17 +187,13 @@ class DefaultTableManager(TableManager[JsonTableData]):
return len(self.data)
def get_num_columns(self) -> int:
- if isinstance(self.data, dict):
- return len(self.data)
- return 1
+ return len(self.data) if isinstance(self.data, dict) else 1
def get_column_names(self) -> List[str]:
if isinstance(self.data, dict):
return list(self.data.keys())
first = next(iter(self.data), None)
- if isinstance(first, dict):
- return list(first.keys())
- return ["value"]
+ return list(first.keys()) if isinstance(first, dict) else ["value"]
def get_unique_column_values(self, column: str) -> list[str | int | float]:
return sorted(
@@ -215,7 +231,7 @@ class DefaultTableManager(TableManager[JsonTableData]):
column_values = data.values()
column_names = list(data.keys())
return [
- {key: value for key, value in zip(column_names, row_values)}
+ dict(zip(column_names, row_values))
for row_values in zip(*column_values)
]
@@ -230,18 +246,16 @@ class DefaultTableManager(TableManager[JsonTableData]):
return []
# Handle single-column data
- if not isinstance(data[0], dict) and isinstance(
- data[0], (str, int, float, bool, type(None))
- ):
+ if not isinstance(data[0], dict):
+ if not isinstance(data[0], (str, int, float, bool, type(None))):
+ raise ValueError(
+ "data must be a sequence of JSON-serializable types, or a "
+ "sequence of dicts."
+ )
+
# we're going to assume that data has the right shape, after
# having checked just the first entry
casted = cast(List[Union[str, int, float, bool, MIME, None]], data)
return [{"value": datum} for datum in casted]
- elif not isinstance(data[0], dict):
- raise ValueError(
- "data must be a sequence of JSON-serializable types, or a "
- "sequence of dicts."
- )
-
# Sequence of dicts
return cast(List[Dict[str, Any]], data)
diff --git a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
index 480024ee82..980a22ed35 100644
--- a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
+++ b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
@@ -9,6 +9,7 @@ from marimo._plugins.ui._impl.tables.dataframe_protocol import (
Column,
DtypeKind,
)
+from marimo._plugins.ui._impl.tables.format import FormatMapping
from marimo._plugins.ui._impl.tables.pyarrow_table import (
PyArrowTableManagerFactory,
)
@@ -56,12 +57,17 @@ class DataFrameProtocolTableManager(TableManager[DataFrameLike]):
)
return self._delegate
+ def apply_formatting( # type: ignore
+ self, format_mapping: FormatMapping
+ ) -> Union[pa.Table, pa.RecordBatch]:
+ return self._ensure_delegate().apply_formatting(format_mapping)
+
def supports_filters(self) -> bool:
# Does't support filters until pyarrow supports it
return False
- def to_csv(self) -> bytes:
- return self._ensure_delegate().to_csv()
+ def to_csv(self, format_mapping: Optional[FormatMapping] = None) -> bytes:
+ return self._ensure_delegate().to_csv(format_mapping)
def to_json(self) -> bytes:
return self._ensure_delegate().to_json()
diff --git a/marimo/_plugins/ui/_impl/tables/format.py b/marimo/_plugins/ui/_impl/tables/format.py
new file mode 100644
index 0000000000..9de139d3c4
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/tables/format.py
@@ -0,0 +1,50 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Callable, Dict, List, Union
+
+from marimo._plugins.core.web_component import JSONType
+
+FormatMapping = Dict[str, Union[str, Callable[..., JSONType]]]
+
+
+def format_value(
+ col: str, value: JSONType, format_mapping: FormatMapping
+) -> JSONType:
+ # Return None if the format mapping is None
+ if format_mapping is None:
+ return value
+ # Return None if the value is None
+ if value is None:
+ return None
+ # Apply formatting logic based on column and value
+ if col in format_mapping:
+ formatter = format_mapping[col]
+ if isinstance(formatter, str):
+ return formatter.format(value)
+ if callable(formatter):
+ return formatter(value)
+ return value
+
+
+def format_row(
+ row: Dict[str, JSONType], format_mapping: FormatMapping
+) -> Dict[str, JSONType]:
+ # Return None if the format mapping is None
+ if format_mapping is None:
+ return row
+ # Apply formatting to each value in a row dictionary
+ return {
+ col: format_value(col, value, format_mapping)
+ for col, value in row.items()
+ }
+
+
+def format_column(
+ col: str, values: List[JSONType], format_mapping: FormatMapping
+) -> List[JSONType]:
+ # Return None if the format mapping is None
+ if format_mapping is None:
+ return values
+ # Apply formatting to each value in a column list
+ return [format_value(col, value, format_mapping) for value in values]
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 29c4ad8506..4f5fc26875 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -1,9 +1,13 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, Tuple
+from typing import Any, Optional, Tuple
from marimo._data.models import ColumnSummary, ExternalDataType
+from marimo._plugins.ui._impl.tables.format import (
+ FormatMapping,
+ format_value,
+)
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
@@ -25,15 +29,33 @@ class PandasTableManagerFactory(TableManagerFactory):
class PandasTableManager(TableManager[pd.DataFrame]):
type = "pandas"
- def to_csv(self) -> bytes:
+ def to_csv(
+ self, format_mapping: Optional[FormatMapping] = None
+ ) -> bytes:
has_headers = len(self.get_row_headers()) > 0
- return self.data.to_csv(
- index=has_headers,
- ).encode("utf-8")
+ if format_mapping:
+ _data = self.apply_formatting(format_mapping)
+ return _data.to_csv(
+ index=has_headers,
+ ).encode("utf-8")
+ return self.data.to_csv(index=has_headers).encode("utf-8")
def to_json(self) -> bytes:
return self.data.to_json(orient="records").encode("utf-8")
+ def apply_formatting(
+ self, format_mapping: FormatMapping
+ ) -> pd.DataFrame:
+ _data = self.data.copy()
+ for col in _data.columns:
+ if col in format_mapping:
+ _data[col] = _data[col].apply(
+ lambda x, col=col: format_value( # type: ignore
+ col, x, format_mapping
+ )
+ )
+ return _data
+
def supports_filters(self) -> bool:
return True
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index 79611adbee..28ab5fa944 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -1,13 +1,17 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, Tuple, cast
+from typing import Any, Optional, Tuple, cast
from marimo._data.models import (
ColumnSummary,
ExternalDataType,
NonNestedLiteral,
)
+from marimo._plugins.ui._impl.tables.format import (
+ FormatMapping,
+ format_value,
+)
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
@@ -29,13 +33,21 @@ class PolarsTableManagerFactory(TableManagerFactory):
class PolarsTableManager(TableManager[pl.DataFrame]):
type = "polars"
- def to_csv(self) -> bytes:
+ def to_csv(
+ self,
+ format_mapping: Optional[FormatMapping] = None,
+ ) -> bytes:
+ _data = (
+ self.apply_formatting(format_mapping)
+ if format_mapping
+ else self.data
+ )
try:
- return self.data.write_csv().encode("utf-8")
+ return _data.write_csv().encode("utf-8")
except pl.exceptions.ComputeError:
# Likely CSV format does not support nested data or objects
# Try to convert columns to json or strings
- result = self.data
+ result = _data
for column in result.get_columns():
dtype = column.dtype
if isinstance(dtype, pl.Struct):
@@ -55,24 +67,41 @@ class PolarsTableManagerFactory(TableManagerFactory):
elif isinstance(dtype, pl.Object):
result = result.with_columns(column.cast(str))
elif isinstance(dtype, pl.Duration):
- if dtype.time_unit == "ns":
+ if dtype.time_unit == "ms":
result = result.with_columns(
- column.dt.total_nanoseconds()
+ column.dt.total_milliseconds()
)
- if dtype.time_unit == "us":
+
+ elif dtype.time_unit == "ns":
result = result.with_columns(
- column.dt.total_microseconds()
+ column.dt.total_nanoseconds()
)
- if dtype.time_unit == "ms":
+ elif dtype.time_unit == "us":
result = result.with_columns(
- column.dt.total_milliseconds()
+ column.dt.total_microseconds()
)
-
return result.write_csv().encode("utf-8")
def to_json(self) -> bytes:
return self.data.write_json().encode("utf-8")
+ def apply_formatting(
+ self, format_mapping: FormatMapping
+ ) -> pl.DataFrame:
+ _data = self.data
+ for col in _data.columns:
+ if col in format_mapping:
+ _data = _data.with_columns(
+ pl.Series(
+ col,
+ [
+ format_value(col, x, format_mapping)
+ for x in _data[col]
+ ],
+ )
+ )
+ return _data
+
def supports_filters(self) -> bool:
return True
@@ -112,7 +141,7 @@ class PolarsTableManagerFactory(TableManagerFactory):
query = query.lower()
expressions = [
- pl.col(column).str.contains("(?i)" + query)
+ pl.col(column).str.contains(f"(?i){query}")
for column in self.data.columns
]
or_expr = expressions[0]
diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
index 0ab3f03212..ee664eabcc 100644
--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
@@ -2,9 +2,13 @@
from __future__ import annotations
import io
-from typing import Any, Tuple, Union, cast
+from typing import Any, Optional, Tuple, Union, cast
from marimo._data.models import ColumnSummary, ExternalDataType
+from marimo._plugins.ui._impl.tables.format import (
+ FormatMapping,
+ format_value,
+)
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
@@ -29,11 +33,16 @@ class PyArrowTableManagerFactory(TableManagerFactory):
):
type = "pyarrow"
- def to_csv(self) -> bytes:
+ def to_csv(
+ self, format_mapping: Optional[FormatMapping] = None
+ ) -> bytes:
import pyarrow.csv as csv # type: ignore
+ _data = self.data
+ if format_mapping:
+ _data = self.apply_formatting(format_mapping)
buffer = io.BytesIO()
- csv.write_csv(self.data, buffer)
+ csv.write_csv(_data, buffer)
return buffer.getvalue()
def to_json(self) -> bytes:
@@ -44,6 +53,55 @@ class PyArrowTableManagerFactory(TableManagerFactory):
.encode("utf-8")
)
+ def apply_formatting(
+ self, format_mapping: FormatMapping
+ ) -> Union[pa.Table, pa.RecordBatch]:
+ _data = self.data
+ if isinstance(_data, pa.Table):
+ column_names = _data.column_names
+ else: # pa.RecordBatch
+ column_names = _data.schema.names
+
+ transformed_columns: list[pa.Array[Any, Any]] = []
+ for i, col in enumerate(column_names):
+ if isinstance(_data, pa.Table):
+ transformed_column = _data.column(i).chunk(0)
+ else:
+ transformed_column = _data.column(i)
+ if col in format_mapping:
+ transformed_values = [
+ format_value(col, value.as_py(), format_mapping)
+ for value in transformed_column
+ ]
+ formatted_type = pa.array(transformed_values).type
+ transformed_column = pa.array(
+ transformed_values, type=formatted_type
+ ) # type: ignore
+
+ # Raise ValueError if transformed_column is pa.ChunkedArray
+ if isinstance(transformed_column, pa.ChunkedArray):
+ raise ValueError(
+ f"Column {col} is a ChunkedArray, "
+ "which is not supported."
+ )
+
+ transformed_columns.append(transformed_column)
+
+ if isinstance(_data, pa.Table):
+ _data = pa.table(transformed_columns, names=column_names)
+ else: # pa.RecordBatch
+ new_schema = pa.schema(
+ [
+ pa.field(col, transformed_columns[i].type)
+ for i, col in enumerate(column_names)
+ ]
+ )
+ _data = pa.RecordBatch.from_arrays(
+ transformed_columns, schema=new_schema
+ ) # type: ignore
+
+ return _data
+
def select_rows(self, indices: list[int]) -> PyArrowTableManager:
if not indices:
return PyArrowTableManager(
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 61540694df..566c58f1cb 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -2,11 +2,19 @@
from __future__ import annotations
import abc
-from typing import Any, Dict, Generic, Optional, Tuple, TypeVar
+from typing import (
+ Any,
+ Dict,
+ Generic,
+ Optional,
+ Tuple,
+ TypeVar,
+)
import marimo._output.data.data as mo_data
from marimo._data.models import ColumnSummary, DataType, ExternalDataType
from marimo._plugins.core.web_component import JSONType
+from marimo._plugins.ui._impl.tables.format import FormatMapping
T = TypeVar("T")
@@ -23,14 +31,17 @@ class TableManager(abc.ABC, Generic[T]):
def __init__(self, data: T) -> None:
self.data = data
- def to_data(self) -> JSONType:
+ def to_data(
+ self,
+ format_mapping: Optional[FormatMapping] = None,
+ ) -> JSONType:
"""
The best way to represent the data in a table as JSON.
By default, this method calls `to_csv` and returns the result as
a string.
"""
- return mo_data.csv(self.to_csv()).url
+ return mo_data.csv(self.to_csv(format_mapping)).url
def supports_download(self) -> bool:
return True
@@ -41,6 +52,10 @@ class TableManager(abc.ABC, Generic[T]):
def supports_altair(self) -> bool:
return True
+ @abc.abstractmethod
+ def apply_formatting(self, format_mapping: FormatMapping) -> T:
+ raise NotImplementedError
+
@abc.abstractmethod
def supports_filters(self) -> bool:
raise NotImplementedError
@@ -52,7 +67,10 @@ class TableManager(abc.ABC, Generic[T]):
raise NotImplementedError
@abc.abstractmethod
- def to_csv(self) -> bytes:
+ def to_csv(
+ self,
+ format_mapping: Optional[FormatMapping] = None,
+ ) -> bytes:
raise NotImplementedError
@abc.abstractmethod
diff --git a/marimo/_smoke_tests/quak-demo.py b/marimo/_smoke_tests/quak-demo.py
index 839c3fe4d6..6fb3eaa3c6 100644
--- a/marimo/_smoke_tests/quak-demo.py
+++ b/marimo/_smoke_tests/quak-demo.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
import marimo
__generated_with = "0.7.12"
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index 7b02ed5deb..68500fe5a9 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -129,6 +129,121 @@ class TestDefaultTable(unittest.TestCase):
]
assert searched_manager.data == expected_data
+ def test_apply_formatting(self) -> None:
+ format_mapping = {
+ "name": lambda x: x.upper(),
+ "age": lambda x: x + 1,
+ "birth_year": lambda x: x.year,
+ }
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ expected_data = [
+ {"name": "ALICE", "age": 31, "birth_year": 1994},
+ {"name": "BOB", "age": 26, "birth_year": 1999},
+ {"name": "CHARLIE", "age": 36, "birth_year": 1989},
+ {"name": "DAVE", "age": 29, "birth_year": 1996},
+ {"name": "EVE", "age": 23, "birth_year": 2002},
+ ]
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_partial(self) -> None:
+ format_mapping = {
+ "age": lambda x: x + 1,
+ }
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ expected_data = [
+ {"name": "Alice", "age": 31, "birth_year": date(1994, 5, 24)},
+ {"name": "Bob", "age": 26, "birth_year": date(1999, 7, 14)},
+ {"name": "Charlie", "age": 36, "birth_year": date(1989, 12, 1)},
+ {"name": "Dave", "age": 29, "birth_year": date(1996, 3, 5)},
+ {"name": "Eve", "age": 23, "birth_year": date(2002, 1, 30)},
+ ]
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_empty(self) -> None:
+ format_mapping = {}
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ assert formatted_manager == self.data
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ format_mapping = {
+ "invalid_column": lambda x: x * 2,
+ }
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ assert formatted_manager == self.data
+
+ def test_apply_formatting_with_nan(self) -> None:
+ data_with_nan = self.data.copy()
+ data_with_nan[1]["age"] = None
+ manager_with_nan = DefaultTableManager(data_with_nan)
+ format_mapping = {
+ "age": lambda x: x + 1 if x is not None else x,
+ }
+ formatted_manager = manager_with_nan.apply_formatting(format_mapping)
+ expected_data = [
+ {"name": "Alice", "age": 31, "birth_year": date(1994, 5, 24)},
+ {"name": "Bob", "age": None, "birth_year": date(1999, 7, 14)},
+ {"name": "Charlie", "age": 36, "birth_year": date(1989, 12, 1)},
+ {"name": "Dave", "age": 29, "birth_year": date(1996, 3, 5)},
+ {"name": "Eve", "age": 23, "birth_year": date(2002, 1, 30)},
+ ]
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_with_mixed_types(self) -> None:
+ data = [
+ {"name": "Alice", "value": 1},
+ {"name": "Bob", "value": "foo"},
+ {"name": "Charlie", "value": 2},
+ {"name": "Dave", "value": False},
+ ]
+ manager = DefaultTableManager(data)
+ format_mapping = {
+ "value": str,
+ }
+ formatted_manager = manager.apply_formatting(format_mapping)
+ expected_data = [
+ {"name": "Alice", "value": "1"},
+ {"name": "Bob", "value": "foo"},
+ {"name": "Charlie", "value": "2"},
+ {"name": "Dave", "value": "False"},
+ ]
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_with_complex_data(self) -> None:
+ data = [
+ {
+ "name": "Alice",
+ "age": 30,
+ "birth_year": date(1994, 5, 24),
+ "score": 1.5,
+ },
+ {
+ "name": "Bob",
+ "age": 25,
+ "birth_year": date(1999, 7, 14),
+ "score": 2.5,
+ },
+ {
+ "name": "Charlie",
+ "age": 35,
+ "birth_year": date(1989, 12, 1),
+ "score": 3.5,
+ },
+ ]
+ manager = DefaultTableManager(data)
+ format_mapping = {
+ "name": lambda x: x.upper(),
+ "age": lambda x: x + 1,
+ "birth_year": lambda x: x.year,
+ "score": lambda x: f"{x:.1f}",
+ }
+ formatted_manager = manager.apply_formatting(format_mapping)
+ expected_data = [
+ {"name": "ALICE", "age": 31, "birth_year": 1994, "score": "1.5"},
+ {"name": "BOB", "age": 26, "birth_year": 1999, "score": "2.5"},
+ {"name": "CHARLIE", "age": 36, "birth_year": 1989, "score": "3.5"},
+ ]
+ assert formatted_manager == expected_data
+
class TestColumnarDefaultTable(unittest.TestCase):
def setUp(self) -> None:
@@ -227,3 +342,112 @@ class TestColumnarDefaultTable(unittest.TestCase):
"age": [30],
"birth_year": [date(1994, 5, 24)],
}
+ assert searched_manager.data == expected_data
+
+ def test_apply_formatting(self) -> None:
+ format_mapping = {
+ "name": lambda x: x.upper(),
+ "age": lambda x: x + 1,
+ "birth_year": lambda x: x.year,
+ }
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ expected_data = {
+ "name": ["ALICE", "BOB", "CHARLIE", "DAVE", "EVE"],
+ "age": [31, 26, 36, 29, 23],
+ "birth_year": [1994, 1999, 1989, 1996, 2002],
+ }
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_partial(self) -> None:
+ format_mapping = {
+ "age": lambda x: x + 1,
+ }
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ expected_data = {
+ "name": ["Alice", "Bob", "Charlie", "Dave", "Eve"],
+ "age": [31, 26, 36, 29, 23],
+ "birth_year": [
+ date(1994, 5, 24),
+ date(1999, 7, 14),
+ date(1989, 12, 1),
+ date(1996, 3, 5),
+ date(2002, 1, 30),
+ ],
+ }
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_empty(self) -> None:
+ format_mapping = {}
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ assert formatted_manager == self.data
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ format_mapping = {
+ "invalid_column": lambda x: x * 2,
+ }
+ formatted_manager = self.manager.apply_formatting(format_mapping)
+ assert formatted_manager == self.data
+
+ def test_apply_formatting_with_nan(self) -> None:
+ data_with_nan = self.data.copy()
+ data_with_nan["age"][1] = None
+ manager_with_nan = DefaultTableManager(data_with_nan)
+ format_mapping = {
+ "age": lambda x: x + 1 if x is not None else x,
+ }
+ formatted_manager = manager_with_nan.apply_formatting(format_mapping)
+ expected_data = {
+ "name": ["Alice", "Bob", "Charlie", "Dave", "Eve"],
+ "age": [31, None, 36, 29, 23],
+ "birth_year": [
+ date(1994, 5, 24),
+ date(1999, 7, 14),
+ date(1989, 12, 1),
+ date(1996, 3, 5),
+ date(2002, 1, 30),
+ ],
+ }
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_with_mixed_types(self) -> None:
+ data = {
+ "name": ["Alice", "Bob", "Charlie", "Dave"],
+ "value": [1, "foo", 2, False],
+ }
+ manager = DefaultTableManager(data)
+ format_mapping = {
+ "value": str,
+ }
+ formatted_manager = manager.apply_formatting(format_mapping)
+ expected_data = {
+ "name": ["Alice", "Bob", "Charlie", "Dave"],
+ "value": ["1", "foo", "2", "False"],
+ }
+ assert formatted_manager == expected_data
+
+ def test_apply_formatting_with_complex_data(self) -> None:
+ data = {
+ "name": ["Alice", "Bob", "Charlie"],
+ "age": [30, 25, 35],
+ "birth_year": [
+ date(1994, 5, 24),
+ date(1999, 7, 14),
+ date(1989, 12, 1),
+ ],
+ "score": [1.5, 2.5, 3.5],
+ }
+ manager = DefaultTableManager(data)
+ format_mapping = {
+ "name": lambda x: x.upper(),
+ "age": lambda x: x + 1,
+ "birth_year": lambda x: x.year,
+ "score": lambda x: f"{x:.1f}",
+ }
+ formatted_manager = manager.apply_formatting(format_mapping)
+ expected_data = {
+ "name": ["ALICE", "BOB", "CHARLIE"],
+ "age": [31, 26, 36],
+ "birth_year": [1994, 1999, 1989],
+ "score": ["1.5", "2.5", "3.5"],
+ }
+ assert formatted_manager == expected_data
diff --git a/tests/_plugins/ui/_impl/tables/test_df_protocol.py b/tests/_plugins/ui/_impl/tables/test_df_protocol.py
index 8ebe28f40b..2071d1d50b 100644
--- a/tests/_plugins/ui/_impl/tables/test_df_protocol.py
+++ b/tests/_plugins/ui/_impl/tables/test_df_protocol.py
@@ -162,3 +162,70 @@ class TestDataFrameProtocolTableManager(unittest.TestCase):
min=datetime.datetime(2021, 1, 1, 0, 0),
max=datetime.datetime(2021, 1, 3, 0, 0),
)
+
+ def test_apply_formatting(self) -> None:
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ }
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pa.table(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ }
+ )
+ assert formatted_data.equals(expected_data)
+
+ def test_apply_formatting_partial(self) -> None:
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pa.table(
+ {
+ "A": [2, 4, 6],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
+ assert formatted_data.equals(expected_data)
+
+ def test_apply_formatting_empty(self) -> None:
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {}
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(self.data)
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "Z": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(self.data)
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 63068f6936..17925c163f 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -366,3 +366,315 @@ class TestPandasTableManager(unittest.TestCase):
assert manager.search("a").get_num_rows() == 2
assert manager.search("true").get_num_rows() == 2
assert manager.search("food").get_num_rows() == 0
+
+ def test_apply_formatting_does_not_modify_original_data(self) -> None:
+ import pandas as pd
+
+ original_data = self.data.copy()
+ format_mapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+ self.manager.apply_formatting(format_mapping)
+ pd.testing.assert_frame_equal(self.manager.data, original_data)
+
+ def test_apply_formatting(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", " B"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ "F": [
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ ], # No formatting applied
+ }
+ )
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_empty_dataframe(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ empty_data = pd.DataFrame()
+ manager = self.factory.create()(empty_data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ pd.testing.assert_frame_equal(formatted_data, empty_data)
+
+ def test_apply_formatting_partial(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["a", "b", " b"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "F": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ }
+ )
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_empty(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {}
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ pd.testing.assert_frame_equal(formatted_data, self.data)
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "Z": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ pd.testing.assert_frame_equal(formatted_data, self.data)
+
+ def test_apply_formatting_with_nan(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data_with_nan = self.data.copy()
+ data_with_nan.loc[1, "A"] = None
+ manager_with_nan = self.factory.create()(data_with_nan)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2 if pd.notna(x) else x,
+ }
+
+ formatted_data = manager_with_nan.apply_formatting(format_mapping)
+ expected_data = data_with_nan.copy()
+ expected_data["A"] = [2, None, 6]
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_mixed_types(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "F": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ "G": [None, "text", 3.14],
+ }
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ "G": str,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ "F": [
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ ], # No formatting applied
+ "G": [None, "text", "3.14"],
+ }
+ )
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_multi_index(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ },
+ index=pd.MultiIndex.from_tuples(
+ [("x", 1), ("y", 2), ("z", 3)], names=["X", "Y"]
+ ),
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ },
+ index=pd.MultiIndex.from_tuples(
+ [("x", 1), ("y", 2), ("z", 3)], names=["X", "Y"]
+ ),
+ )
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_categorical_data(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pd.DataFrame(
+ {
+ "A": pd.Categorical(["a", "b", "a"]),
+ "B": [1, 2, 3],
+ }
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x.upper(),
+ "B": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pd.DataFrame(
+ {
+ "A": pd.Categorical(["A", "B", "A"]),
+ "B": [2, 4, 6],
+ }
+ )
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_datetime_index(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ },
+ index=pd.to_datetime(["2021-01-01", "2021-01-02", "2021-01-03"]),
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ },
+ index=pd.to_datetime(["2021-01-01", "2021-01-02", "2021-01-03"]),
+ )
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_complex_data(self) -> None:
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "F": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ "G": [None, "text", 3.14],
+ "H": [1 + 2j, 3 + 4j, 5 + 6j],
+ }
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ "G": str,
+ "H": abs,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ "F": [
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ ], # No formatting applied
+ "G": [None, "text", "3.14"],
+ "H": [2.23606797749979, 5.0, 7.810249675906654],
+ }
+ )
+ pd.testing.assert_frame_equal(formatted_data, expected_data)
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 635c91d715..6f15d29d72 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -306,3 +306,279 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
assert manager.search("a").get_num_rows() == 2
assert manager.search("true").get_num_rows() == 2
assert manager.search("food").get_num_rows() == 0
+
+ def test_apply_formatting_does_not_modify_original_data(self) -> None:
+ from polars.testing import assert_frame_equal
+
+ original_data = self.data.clone()
+ format_mapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+ self.manager.apply_formatting(format_mapping)
+ assert_frame_equal(self.manager.data, original_data)
+
+ def test_apply_formatting(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_empty_dataframe(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ empty_data = pl.DataFrame()
+ manager = self.factory.create()(empty_data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ assert_frame_equal(formatted_data, empty_data)
+
+ def test_apply_formatting_partial(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_empty(self) -> None:
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {}
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert_frame_equal(formatted_data, self.data)
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "Z": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert_frame_equal(formatted_data, self.data)
+
+ def test_apply_formatting_with_nan(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data_with_nan = self.data.clone()
+ data_with_nan = data_with_nan.with_columns(
+ pl.when(pl.col("A").is_not_null())
+ .then(pl.col("A"))
+ .otherwise(None)
+ .alias("A")
+ )
+ manager_with_nan = self.factory.create()(data_with_nan)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2 if x is not None else x,
+ }
+
+ formatted_data = manager_with_nan.apply_formatting(format_mapping)
+ expected_data = data_with_nan.clone()
+ expected_data = expected_data.with_columns(
+ pl.when(pl.col("A").is_not_null())
+ .then(pl.col("A") * 2)
+ .otherwise(None)
+ .alias("A")
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_multi_index(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ }
+ ).with_row_count("index")
+ data = data.with_columns(pl.col("index").cast(pl.Utf8))
+
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "index": ["0", "1", "2"],
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_categorical_data(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pl.DataFrame(
+ {
+ "A": pl.Series(["a", "b", "a"]).cast(pl.Categorical),
+ "B": [1, 2, 3],
+ }
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x.upper(),
+ "B": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": pl.Series(["A", "B", "A"]),
+ "B": [2, 4, 6],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_datetime_index(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ }
+ ).with_columns(
+ pl.date_range(
+ start=datetime.datetime(2021, 1, 1),
+ end=datetime.datetime(2021, 1, 3),
+ interval="1d",
+ ).alias("index")
+ )
+ data = data.with_columns(pl.col("index").cast(pl.Utf8))
+
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "index": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_complex_data(self) -> None:
+ import polars as pl
+ from polars.testing import assert_frame_equal
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ data = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "F": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ "G": [1 + 2j, 3 + 4j, 5 + 6j],
+ }
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ "G": abs,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ "F": [
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ ], # No formatting applied
+ "G": [2.23606797749979, 5.0, 7.810249675906654],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
diff --git a/tests/_plugins/ui/_impl/tables/test_pyarrow.py b/tests/_plugins/ui/_impl/tables/test_pyarrow.py
index 61ce4045e8..f6ade0e3ed 100644
--- a/tests/_plugins/ui/_impl/tables/test_pyarrow.py
+++ b/tests/_plugins/ui/_impl/tables/test_pyarrow.py
@@ -11,10 +11,15 @@ from marimo._plugins.ui._impl.tables.pyarrow_table import (
PyArrowTableManagerFactory,
)
-HAS_DEPS = DependencyManager.has_pyarrow()
+HAS_DEPS_TABLE = DependencyManager.has_pyarrow()
+HAS_DEPS_RECORD_BATCH = (
+ DependencyManager.has_pandas() and DependencyManager.has_pyarrow()
+)
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ not HAS_DEPS_TABLE, reason="optional dependencies not installed"
+)
class TestPyArrowTableManagerFactory(unittest.TestCase):
def setUp(self) -> None:
import pyarrow as pa
@@ -182,3 +187,348 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):
assert manager.search("aaa").get_num_rows() == 1
assert manager.search("true").get_num_rows() == 2
assert manager.search("baz").get_num_rows() == 0
+
+ def test_apply_formatting(self) -> None:
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pa.table(
+ {
+ "A": [2, 4, 6],
+ "B": ["AAA", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ }
+ )
+ assert formatted_data.equals(expected_data)
+
+ def test_apply_formatting_with_empty_table(self) -> None:
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ empty_data = pa.table({})
+ manager = self.factory.create()(empty_data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(empty_data)
+
+ def test_apply_formatting_partial(self) -> None:
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pa.table(
+ {
+ "A": [2, 4, 6],
+ "B": ["aaa", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
+ assert formatted_data.equals(expected_data)
+
+ def test_apply_formatting_empty(self) -> None:
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {}
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(self.data)
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "Z": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(self.data)
+
+
+ not HAS_DEPS_RECORD_BATCH, reason="optional dependencies not installed"
+)
+class TestPyArrowRecordBatchManagerFactory(unittest.TestCase):
+ def setUp(self) -> None:
+ import pandas as pd
+ import pyarrow as pa
+
+ self.factory = PyArrowTableManagerFactory()
+ self.data = pa.RecordBatch.from_pandas(
+ pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["aaa", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
+ )
+ self.manager = self.factory.create()(self.data)
+
+ def test_package_name(self) -> None:
+ assert self.factory.package_name() == "pyarrow"
+
+ def test_to_csv(self) -> None:
+ assert isinstance(self.manager.to_csv(), bytes)
+
+ def test_to_json(self) -> None:
+ assert isinstance(self.manager.to_json(), bytes)
+
+ def test_select_rows(self) -> None:
+ indices = [0, 2]
+ selected_manager = self.manager.select_rows(indices)
+ expected_data = self.data.take(indices)
+ assert selected_manager.data == expected_data
+
+ def test_select_rows_empty(self) -> None:
+ selected_manager = self.manager.select_rows([])
+ assert selected_manager.data.num_rows == 0
+
+ def test_select_columns(self) -> None:
+ columns = ["A"]
+ selected_manager = self.manager.select_columns(columns)
+ expected_data = self.data.select(columns)
+ assert selected_manager.data == expected_data
+
+ def test_get_row_headers(self) -> None:
+ expected_headers = []
+ assert self.manager.get_row_headers() == expected_headers
+
+ def test_is_type(self) -> None:
+ assert self.manager.is_type(self.data)
+ assert not self.manager.is_type("not a dataframe")
+
+ def test_get_field_types(self) -> None:
+ import pandas as pd
+ import pyarrow as pa
+
+ expected_field_types = {
+ "A": ("integer", "int64"),
+ "B": ("string", "string"),
+ "C": ("number", "double"),
+ "D": ("boolean", "bool"),
+ "E": ("date", "timestamp[ns]"),
+ }
+ assert self.manager.get_field_types() == expected_field_types
+
+ complex_data = pa.RecordBatch.from_pandas(
+ pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["aaa", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [None, None, None],
+ }
+ )
+ )
+ expected_field_types = {
+ "A": ("integer", "int64"),
+ "B": ("string", "string"),
+ "C": ("number", "double"),
+ "D": ("boolean", "bool"),
+ "E": ("unknown", "null"),
+ }
+ assert (
+ self.factory.create()(complex_data).get_field_types()
+ == expected_field_types
+ )
+
+ def test_limit(self) -> None:
+ limited_manager = self.manager.limit(1)
+ expected_data = self.data.slice(0, 1)
+ assert limited_manager.data == expected_data
+
+ def test_limit_more_than_num_rows(self) -> None:
+ limited_manager = self.manager.limit(500)
+ assert limited_manager.data == self.data
+
+ def test_summary_integer(self) -> None:
+ column = "A"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ min=1,
+ max=3,
+ mean=2.0,
+ )
+
+ def test_summary_string(self) -> None:
+ column = "B"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ )
+
+ def test_summary_number(self) -> None:
+ column = "C"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=1.0,
+ max=3.0,
+ mean=2.0,
+ )
+
+ def test_summary_boolean(self) -> None:
+ column = "D"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ true=2,
+ false=1,
+ )
+
+ def test_summary_date(self) -> None:
+ column = "E"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=datetime.datetime(2021, 1, 1, 0, 0),
+ max=datetime.datetime(2021, 1, 3, 0, 0),
+ )
+
+ def test_sort_values(self) -> None:
+ sorted_df = self.manager.sort_values("A", descending=True).data
+ expected_df = self.data.sort_by([("A", "descending")])
+ assert sorted_df.equals(expected_df)
+
+ def test_get_unique_column_values(self) -> None:
+ column = "B"
+ unique_values = self.manager.get_unique_column_values(column)
+ assert unique_values == ["aaa", "b", "c"]
+
+ def test_search(self) -> None:
+ manager = self.factory.create()(self.data)
+ assert manager.search("aaa").get_num_rows() == 1
+ assert manager.search("true").get_num_rows() == 2
+ assert manager.search("baz").get_num_rows() == 0
+
+ def test_apply_formatting(self) -> None:
+ import pandas as pd
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ }
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pa.RecordBatch.from_pandas(
+ pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["AAA", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ }
+ )
+ )
+ assert formatted_data.equals(expected_data)
+
+ def test_apply_formatting_with_empty_table(self) -> None:
+ import pandas as pd
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ empty_data = pa.RecordBatch.from_pandas(pd.DataFrame({}))
+ manager = self.factory.create()(empty_data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(empty_data)
+
+ def test_apply_formatting_partial(self) -> None:
+ import pandas as pd
+ import pyarrow as pa
+
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pa.RecordBatch.from_pandas(
+ pd.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["aaa", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
+ )
+ assert formatted_data.equals(expected_data)
+
+ def test_apply_formatting_empty(self) -> None:
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {}
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(self.data)
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ from marimo._plugins.ui._impl.tables.format import FormatMapping
+
+ format_mapping: FormatMapping = {
+ "Z": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert formatted_data.equals(self.data)
diff --git a/tests/_plugins/ui/_impl/tables/test_table_utils.py b/tests/_plugins/ui/_impl/tables/test_table_utils.py
index 696413702e..d558bd5410 100644
--- a/tests/_plugins/ui/_impl/tables/test_table_utils.py
+++ b/tests/_plugins/ui/_impl/tables/test_table_utils.py
@@ -5,6 +5,11 @@ import pytest
from marimo._plugins.ui._impl.tables.df_protocol_table import (
DataFrameProtocolTableManager,
)
+from marimo._plugins.ui._impl.tables.format import (
+ format_column,
+ format_row,
+ format_value,
+)
from marimo._plugins.ui._impl.tables.types import is_dataframe_like
@@ -39,3 +44,112 @@ def test_is_dataframe_like():
def test_df_protocol_manager_throws():
with pytest.raises(ValueError):
DataFrameProtocolTableManager(Real())
+
+
+def test_format_value():
+ # Test with string formatter
+ format_mapping = {"col1": "{:.2f}"}
+ assert format_value("col1", 123.456, format_mapping) == "123.46"
+
+ # Test with callable formatter
+ format_mapping = {"col1": lambda x: f"${x:.2f}"}
+ assert format_value("col1", 123.456, format_mapping) == "$123.46"
+
+ # Test with no formatter
+ format_mapping = {}
+ assert format_value("col1", 123.456, format_mapping) == 123.456
+
+ # Test with non-existent column
+ format_mapping = {"col2": "{:.2f}"}
+ assert format_value("col1", 123.456, format_mapping) == 123.456
+
+ # Test with None value
+ format_mapping = {"col1": "{:.2f}"}
+ assert format_value("col1", None, format_mapping) is None
+
+ # Test with empty string formatter
+ format_mapping = {"col1": ""}
+ assert format_value("col1", 123.456, format_mapping) == ""
+
+ # Test with complex callable formatter
+ format_mapping = {"col1": lambda x: f"{x:.2f} units"}
+ assert format_value("col1", 123.456, format_mapping) == "123.46 units"
+
+
+def test_format_row():
+ # Test with string formatter
+ format_mapping = {"col1": "{:.2f}", "col2": "{:.1f}"}
+ row = {"col1": 123.456, "col2": 78.9}
+ expected = {"col1": "123.46", "col2": "78.9"}
+ assert format_row(row, format_mapping) == expected
+
+ # Test with callable formatter
+ format_mapping = {
+ "col1": lambda x: f"${x:.2f}",
+ "col2": lambda x: f"{x:.1f}%",
+ }
+ row = {"col1": 123.456, "col2": 78.9}
+ expected = {"col1": "$123.46", "col2": "78.9%"}
+ assert format_row(row, format_mapping) == expected
+
+ # Test with mixed formatter
+ format_mapping = {"col1": "{:.2f}", "col2": lambda x: f"{x:.1f}%"}
+ row = {"col1": 123.456, "col2": 78.9}
+ expected = {"col1": "123.46", "col2": "78.9%"}
+ assert format_row(row, format_mapping) == expected
+
+ # Test with no formatter
+ format_mapping = {}
+ row = {"col1": 123.456, "col2": 78.9}
+ expected = {"col1": 123.456, "col2": 78.9}
+ assert format_row(row, format_mapping) == expected
+
+ # Test with missing column in row
+ format_mapping = {"col1": "{:.2f}", "col3": "{:.1f}"}
+ row = {"col1": 123.456, "col2": 78.9}
+ expected = {"col1": "123.46", "col2": 78.9}
+ assert format_row(row, format_mapping) == expected
+
+ # Test with None value in row
+ format_mapping = {"col1": "{:.2f}", "col2": "{:.1f}"}
+ row = {"col1": None, "col2": 78.9}
+ expected = {"col1": None, "col2": "78.9"}
+ assert format_row(row, format_mapping) == expected
+
+
+def test_format_column():
+ # Test with string formatter
+ format_mapping = {"col1": "{:.2f}"}
+ values = [123.456, 78.9]
+ expected = ["123.46", "78.90"]
+ assert format_column("col1", values, format_mapping) == expected
+
+ # Test with callable formatter
+ format_mapping = {"col1": lambda x: f"${x:.2f}"}
+ values = [123.456, 78.9]
+ expected = ["$123.46", "$78.90"]
+ assert format_column("col1", values, format_mapping) == expected
+
+ # Test with no formatter
+ format_mapping = {}
+ values = [123.456, 78.9]
+ expected = [123.456, 78.9]
+ assert format_column("col1", values, format_mapping) == expected
+
+ # Test with non-existent column
+ format_mapping = {"col2": "{:.2f}"}
+ values = [123.456, 78.9]
+ expected = [123.456, 78.9]
+ assert format_column("col1", values, format_mapping) == expected
+
+ # Test with None value in column
+ format_mapping = {"col1": "{:.2f}"}
+ values = [123.456, None]
+ expected = ["123.46", None]
+ assert format_column("col1", values, format_mapping) == expected
+
+ # Test with empty list
+ format_mapping = {"col1": "{:.2f}"}
+ values = []
+ expected = []
+ assert format_column("col1", values, format_mapping) == expected