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.

improvement: add row headers (#232)

Myles Scolnickb7a295f67249
diff --git a/examples/dashboards/movies.py b/examples/dashboards/movies.py
index 276bde6805..73cd6d477e 100644
--- a/examples/dashboards/movies.py
+++ b/examples/dashboards/movies.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.1.30"
+__generated_with = "0.1.33"
app = marimo.App(width="full")
@@ -185,7 +185,12 @@ def __(
@app.cell
def __(filtered_movies, mo):
- mo.ui.table(filtered_movies, selection=None)
+ mo.tabs(
+ {
+ "📑 Data": mo.ui.table(filtered_movies, selection=None, page_size=5),
+ "📊 Summary": mo.ui.table(filtered_movies.describe(), selection=None),
+ }
+ )
return
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index ad576cde79..bb8c7f93c0 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -55,6 +55,7 @@ export function getColumnInfo<T>(items: T[]): ColumnInfo[] {
export function generateColumns<T>(
items: T[],
+ rowHeaders: Array<ColumnDef<T>>,
selection: "single" | "multi" | null
): Array<ColumnDef<T>> {
const columnInfo = getColumnInfo(items);
@@ -82,6 +83,10 @@ export function generateColumns<T>(
})
);
+ if (rowHeaders.length > 0) {
+ columns.unshift(...rowHeaders);
+ }
+
if (selection === "single" || selection === "multi") {
columns.unshift({
id: "select",
@@ -111,6 +116,29 @@ export function generateColumns<T>(
return columns;
}
+/**
+ * Turn rowHeaders into a list of columns
+ */
+export function generateIndexColumns<T>(
+ rowHeaders: Array<[string, string[]]>
+): Array<ColumnDef<T>> {
+ return rowHeaders.map(
+ ([title, keys], idx): ColumnDef<T> => ({
+ id: `_row_header_${idx}`,
+ accessorFn: (_row, idx) => {
+ return keys[idx];
+ },
+ header: ({ column }) => {
+ return <DataTableColumnHeader title={title} column={column} />;
+ },
+ cell: ({ renderValue }) => {
+ return <b>{String(renderValue())}</b>;
+ },
+ enableSorting: false,
+ })
+ );
+}
+
function isPrimitiveOrNullish(value: unknown): boolean {
if (value == null) {
return true;
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index f5f268fae3..507b7c39d1 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -3,6 +3,7 @@ import React from "react";
import {
ColumnDef,
OnChangeFn,
+ PaginationState,
RowSelectionState,
SortingState,
flexRender,
@@ -27,6 +28,7 @@ interface DataTableProps<TData, TValue> extends Partial<DownloadActionProps> {
columns: Array<ColumnDef<TData, TValue>>;
data: TData[];
pagination?: boolean;
+ pageSize?: number;
selection?: "single" | "multi" | null;
rowSelection?: RowSelectionState;
onRowSelectionChange?: OnChangeFn<RowSelectionState>;
@@ -36,22 +38,33 @@ export const DataTable = <TData, TValue>({
columns,
data,
rowSelection,
+ pageSize = 10,
downloadAs,
pagination = false,
onRowSelectionChange,
}: DataTableProps<TData, TValue>) => {
const [sorting, setSorting] = React.useState<SortingState>([]);
+ const [paginationState, setPaginationState] = React.useState<PaginationState>(
+ { pageSize: pageSize, pageIndex: 0 }
+ );
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
+ // pagination
+ onPaginationChange: setPaginationState,
getPaginationRowModel: pagination ? getPaginationRowModel() : undefined,
+ // sorting
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
+ // selection
onRowSelectionChange: onRowSelectionChange,
state: {
sorting,
+ pagination: pagination
+ ? { ...paginationState, pageSize: pageSize }
+ : { pageIndex: 0, pageSize: data.length },
rowSelection,
},
});
diff --git a/frontend/src/plugins/core/BadPlugin.tsx b/frontend/src/plugins/core/BadPlugin.tsx
index 2f700b8674..08119f5621 100644
--- a/frontend/src/plugins/core/BadPlugin.tsx
+++ b/frontend/src/plugins/core/BadPlugin.tsx
@@ -2,12 +2,26 @@
import { ZodError } from "zod";
import { Alert } from "../../components/ui/alert";
import { AlertTitle } from "../../components/ui/alert";
+import {
+ Accordion,
+ AccordionItem,
+ AccordionTrigger,
+ AccordionContent,
+} from "@radix-ui/react-accordion";
+import { JsonOutput } from "@/editor/output/JsonOutput";
+import { EmotionCacheProvider } from "@/editor/output/EmotionCacheProvider";
interface Props {
error: ZodError | Error;
+ shadowRoot: ShadowRoot | null;
+ badData: Record<string, unknown>;
}
-export const BadPluginData: React.FC<Props> = ({ error }) => {
+export const BadPluginData: React.FC<Props> = ({
+ error,
+ badData,
+ shadowRoot,
+}) => {
if (error instanceof ZodError) {
return (
<Alert variant="destructive">
@@ -24,6 +38,21 @@ export const BadPluginData: React.FC<Props> = ({ error }) => {
})}
</ul>
</div>
+ <Accordion type="single" collapsible={true}>
+ <AccordionItem
+ value="item-1"
+ className="text-muted-foreground border-muted-foreground-20"
+ >
+ <AccordionTrigger className="py-2 text-[0.84375rem]">
+ View Data:
+ </AccordionTrigger>
+ <AccordionContent className="text-[0.84375rem]">
+ <EmotionCacheProvider container={shadowRoot}>
+ <JsonOutput data={badData} />
+ </EmotionCacheProvider>
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
</Alert>
);
}
@@ -31,6 +60,12 @@ export const BadPluginData: React.FC<Props> = ({ error }) => {
return <div>{error.message}</div>;
};
-export function renderError(error: ZodError | Error): JSX.Element {
- return <BadPluginData error={error} />;
+export function renderError(
+ error: ZodError | Error,
+ badData: Record<string, unknown>,
+ shadowRoot: ShadowRoot | null
+): JSX.Element {
+ return (
+ <BadPluginData error={error} badData={badData} shadowRoot={shadowRoot} />
+ );
}
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index eb1640fab8..24395a88f9 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -187,7 +187,13 @@ function PluginSlotInternal<T>(
// If we failed to parse the initial value, render an error
if (!parseResult.success) {
- return renderError(parseResult.error);
+ return renderError(
+ parseResult.error,
+ Objects.mapValues(hostElement.dataset, (value) =>
+ typeof value === "string" ? parseAttrValue(value) : value
+ ),
+ hostElement.shadowRoot
+ );
}
// Render the plugin
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 6999bf2d16..082cab9edc 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -5,7 +5,10 @@ import { z } from "zod";
import { loader as createLoader, read } from "vega-loader";
import { DataTable } from "../../components/data-table/data-table";
-import { generateColumns } from "../../components/data-table/columns";
+import {
+ generateColumns,
+ generateIndexColumns,
+} from "../../components/data-table/columns";
import { Labeled } from "./common/labeled";
import { useAsyncData } from "@/hooks/useAsyncData";
import { Alert, AlertTitle } from "@/components/ui/alert";
@@ -22,8 +25,10 @@ interface Data<T> {
label: string | null;
data: T[] | string;
pagination: boolean;
+ pageSize: number;
selection: "single" | "multi" | null;
showDownload: boolean;
+ rowHeaders: Array<[string, string[]]>;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
@@ -42,8 +47,10 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
label: z.string().nullable(),
data: z.union([z.string(), z.array(z.object({}).passthrough())]),
pagination: z.boolean().default(false),
+ pageSize: z.number().default(10),
selection: z.enum(["single", "multi"]).nullable().default(null),
showDownload: z.boolean().default(false),
+ rowHeaders: z.array(z.tuple([z.string(), z.array(z.any())])),
})
)
.withFunctions<Functions>({
@@ -111,17 +118,19 @@ const DataTableComponent = ({
label,
data,
pagination,
+ pageSize,
selection,
value,
showDownload,
+ rowHeaders,
download_as: downloadAs,
setValue,
}: DataTableProps & {
data: unknown[];
}): JSX.Element => {
const columns = useMemo(
- () => generateColumns(data, selection),
- [data, selection]
+ () => generateColumns(data, generateIndexColumns(rowHeaders), selection),
+ [data, selection, rowHeaders]
);
const rowSelection = Object.fromEntries((value || []).map((v) => [v, true]));
@@ -132,6 +141,7 @@ const DataTableComponent = ({
data={data}
columns={columns}
pagination={pagination}
+ pageSize={pageSize}
rowSelection={rowSelection}
downloadAs={showDownload ? downloadAs : undefined}
onRowSelectionChange={(updater) => {
diff --git a/frontend/src/stories/data-table.stories.mdx b/frontend/src/stories/data-table.stories.mdx
index 145b4743b9..4ab1349eb4 100644
--- a/frontend/src/stories/data-table.stories.mdx
+++ b/frontend/src/stories/data-table.stories.mdx
@@ -13,20 +13,28 @@ import { generateColumns } from "@/components/data-table/columns";
{ first_name: "Michael", last_name: "Scott" },
{ first_name: "Dwight", last_name: "Schrute" },
]}
- columns={generateColumns([
- { first_name: "Michael", last_name: "Scott" },
- { first_name: "Dwight", last_name: "Schrute" },
- ])}
+ columns={generateColumns(
+ [
+ { first_name: "Michael", last_name: "Scott" },
+ { first_name: "Dwight", last_name: "Schrute" },
+ ],
+ [],
+ null
+ )}
/>
</Story>
<Story name="Empty 1">
<DataTable
data={[]}
- columns={generateColumns([
- { first_name: "Michael", last_name: "Scott" },
- { first_name: "Dwight", last_name: "Schrute" },
- ])}
+ columns={generateColumns(
+ [
+ { first_name: "Michael", last_name: "Scott" },
+ { first_name: "Dwight", last_name: "Schrute" },
+ ],
+ [],
+ null
+ )}
/>
</Story>
@@ -40,10 +48,14 @@ import { generateColumns } from "@/components/data-table/columns";
{ first_name: "Michael", last_name: "Scott" },
{ first_name: "Dwight", last_name: "Schrute" },
]}
- columns={generateColumns([
- { first_name: "Michael", last_name: "Scott" },
- { first_name: "Dwight", last_name: "Schrute" },
- ])}
+ columns={generateColumns(
+ [
+ { first_name: "Michael", last_name: "Scott" },
+ { first_name: "Dwight", last_name: "Schrute" },
+ ],
+ [],
+ null
+ )}
pagination={true}
/>
</Story>
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 4be1a5d3a7..ee51c8c46b 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
+ Any,
Callable,
Dict,
Final,
@@ -85,6 +86,8 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
`mo.ui.button(...)`, `mo.md(...)`, `mo.as_html(...)`, etc.
- `pagination`: whether to paginate; if `False`, all rows will be shown
defaults to `True` when above 10 rows, `False` otherwise
+ - `page_size`: the number of rows to show per page.
+ defaults to 10
- `selection`: 'single' or 'multi' to enable row selection, or `None` to
disable
- `label`: text label for the element
@@ -102,6 +105,7 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
],
pagination: Optional[bool] = None,
selection: Optional[Literal["single", "multi"]] = "multi",
+ page_size: int = 10,
*,
label: str = "",
on_change: Optional[
@@ -123,8 +127,10 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
args={
"data": normalized_data,
"pagination": pagination,
+ "page-size": page_size,
"selection": selection,
"show-download": DependencyManager.has_pandas(),
+ "row-headers": _get_row_headers(data),
},
on_change=on_change,
functions=(
@@ -207,3 +213,48 @@ def _normalize_data(data: TableData) -> JSONType:
# Sequence of dicts
return data
+
+
+def _get_row_headers(
+ data: TableData,
+) -> List[tuple[str, List[str | int | float]]]:
+ if DependencyManager.has_pandas():
+ import pandas as pd
+
+ if isinstance(data, pd.DataFrame):
+ return _get_row_headers_for_index(data.index)
+ return []
+
+
+def _get_row_headers_for_index(
+ index: pd.Index[Any],
+) -> List[tuple[str, List[str | int | float]]]:
+ import pandas as pd
+
+ if isinstance(index, pd.RangeIndex):
+ return []
+
+ if isinstance(index, pd.MultiIndex):
+ # recurse
+ headers = []
+ for i in range(index.nlevels):
+ headers.extend(
+ _get_row_headers_for_index(index.get_level_values(i))
+ )
+ return headers
+
+ # we only care about the index if it has a name
+ # or if it is type 'object'
+ # otherwise, it may look like meaningless number
+ if isinstance(index, pd.Index):
+ dtype = str(index.dtype)
+ if (
+ index.name
+ or dtype == "object"
+ or dtype == "string"
+ or dtype == "category"
+ ):
+ name = str(index.name) if index.name else ""
+ return [(name, index.tolist())] # type: ignore[list-item]
+
+ return []
diff --git a/marimo/_plugins/ui/_impl/test_table.py b/marimo/_plugins/ui/_impl/test_table.py
index da30739da5..7593a4f454 100644
--- a/marimo/_plugins/ui/_impl/test_table.py
+++ b/marimo/_plugins/ui/_impl/test_table.py
@@ -1,7 +1,13 @@
# Copyright 2023 Marimo. All rights reserved.
-from typing import Any
+from __future__ import annotations
-from marimo._plugins.ui._impl.table import TableData, _normalize_data
+from typing import Any, List
+
+from marimo._plugins.ui._impl.table import (
+ TableData,
+ _get_row_headers,
+ _normalize_data,
+)
from marimo._runtime.conftest import MockedKernel
from marimo._runtime.runtime import ExecutionContext
@@ -72,3 +78,48 @@ def test_normalize_data() -> None:
== "data must be a sequence of JSON-serializable types, or a "
+ "sequence of dicts."
)
+
+
+def test_get_row_headers() -> None:
+ try:
+ import pandas as pd
+
+ expected: List[tuple[str, List[str]]]
+
+ # Test with pandas DataFrame
+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ df.index.name = "Index"
+ assert _get_row_headers(df) == []
+
+ # Test with non-DataFrame input
+ assert _get_row_headers([1, 2, 3]) == []
+
+ # Test with MultiIndex
+ arrays = [
+ ["foo", "bar", "baz"],
+ ["one", "two", "three"],
+ ]
+ df_multi = pd.DataFrame({"A": range(3)}, index=arrays)
+ expected = [
+ ("", ["foo", "bar", "baz"]),
+ ("", ["one", "two", "three"]),
+ ]
+ assert _get_row_headers(df_multi) == expected
+
+ # Test with RangeIndex
+ df_range = pd.DataFrame({"A": range(3)})
+ assert _get_row_headers(df_range) == []
+
+ # Test with categorical Index
+ df_cat = pd.DataFrame({"A": range(3)})
+ df_cat.index = pd.CategoricalIndex(["a", "b", "c"])
+ expected = [("", ["a", "b", "c"])]
+ assert _get_row_headers(df_cat) == expected
+
+ # Test with named categorical Index
+ df_cat = pd.DataFrame({"A": range(3)})
+ df_cat.index = pd.CategoricalIndex(["a", "b", "c"], name="Colors")
+ expected = [("Colors", ["a", "b", "c"])]
+ assert _get_row_headers(df_cat) == expected
+ except ImportError:
+ pass