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 index column for stable selection in table, persist across search/filter/sort (#3810)

Myles Scolnick860a74f99efe
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsx
index 28f81f5017..235f9ca6ed 100644
--- a/frontend/src/components/data-table/TableActions.tsx
+++ b/frontend/src/components/data-table/TableActions.tsx
@@ -57,7 +57,7 @@ export const TableActions = <TData,>({
? (value: boolean) => {
if (value) {
const allKeys = Array.from(
- { length: table.getRowModel().rows.length },
+ { length: table.getRowCount() },
(_, i) => [i, true] as const,
);
onRowSelectionChange(Object.fromEntries(allKeys));
diff --git a/frontend/src/components/data-table/__test__/columns.test.tsx b/frontend/src/components/data-table/__test__/columns.test.tsx
index b94c8b2e89..5ab44c02bf 100644
--- a/frontend/src/components/data-table/__test__/columns.test.tsx
+++ b/frontend/src/components/data-table/__test__/columns.test.tsx
@@ -229,4 +229,16 @@ describe("generateColumns", () => {
});
expect(cell?.props.className).toContain("center");
});
+
+ it("should not include index column if it exists", () => {
+ const columns = generateColumns({
+ rowHeaders: [],
+ selection: null,
+ fieldTypes: [...fieldTypes, ["_marimo_row_id", ["string", "text"]]],
+ });
+
+ expect(columns).toHaveLength(2);
+ expect(columns[0].id).toBe("name");
+ expect(columns[1].id).toBe("age");
+ });
});
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index dc052c57cc..f924669b5e 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -11,7 +11,7 @@ import { isMimeValue, MimeCell } from "./mime-cell";
import type { DataType } from "@/core/kernel/messages";
import { TableColumnSummary } from "./column-summary";
import type { FilterType } from "./filters";
-import type { FieldTypesWithExternalType } from "./types";
+import { INDEX_COLUMN_NAME, type FieldTypesWithExternalType } from "./types";
import { UrlDetector } from "./url-detector";
import { cn } from "@/utils/cn";
import { uniformSample } from "./uniformSample";
@@ -121,6 +121,13 @@ export function generateColumns<T>({
...rowHeaders,
...fieldTypes.map(([columnName]) => columnName),
];
+
+ // Remove the index column if it exists
+ const indexColumnIdx = columnKeys.indexOf(INDEX_COLUMN_NAME);
+ if (indexColumnIdx !== -1) {
+ columnKeys.splice(indexColumnIdx, 1);
+ }
+
const columns = columnKeys.map(
(key, idx): ColumnDef<T> => ({
id: key || `${NAMELESS_COLUMN_PREFIX}${idx}`,
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index 398990657a..49c49d86b3 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -29,6 +29,7 @@ import { SearchBar } from "./SearchBar";
import { TableActions } from "./TableActions";
import { ColumnFormattingFeature } from "./column-formatting/feature";
import { ColumnWrappingFeature } from "./column-wrapping/feature";
+import { INDEX_COLUMN_NAME } from "./types";
interface DataTableProps<TData> extends Partial<DownloadActionProps> {
wrapperClassName?: string;
@@ -108,10 +109,16 @@ const DataTableInternal = <TData,>({
...(setPaginationState
? {
onPaginationChange: setPaginationState,
- getRowId: (_row, idx) => {
+ getRowId: (row, idx) => {
+ // Prefer stable row ID if it exists
+ if (row && typeof row === "object" && INDEX_COLUMN_NAME in row) {
+ return String(row[INDEX_COLUMN_NAME]);
+ }
+
if (!paginationState) {
return String(idx);
}
+
// Add offset if manualPagination is enabled
const offset = manualPagination
? paginationState.pageIndex * paginationState.pageSize
diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.ts
index 7bbd07c3b4..1fc4b82991 100644
--- a/frontend/src/components/data-table/types.ts
+++ b/frontend/src/components/data-table/types.ts
@@ -29,3 +29,5 @@ export function toFieldTypes(
}
export const SELECT_COLUMN_ID = "__select__";
+
+export const INDEX_COLUMN_NAME = "_marimo_row_id";
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 6c956a94da..0bfe6b2dd3 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -18,6 +18,7 @@ import { ColumnChartContext } from "@/components/data-table/column-summary";
import { Logger } from "@/utils/Logger";
import {
+ INDEX_COLUMN_NAME,
toFieldTypes,
type ColumnHeaderSummary,
type FieldTypesWithExternalType,
@@ -44,7 +45,7 @@ import { useAsyncData } from "@/hooks/useAsyncData";
import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
import { DelayMount } from "@/components/utils/delay-mount";
import { DATA_TYPES } from "@/core/kernel/messages";
-import { useEffectSkipFirstRender } from "../../hooks/useEffectSkipFirstRender";
+import { useEffectSkipFirstRender } from "@/hooks/useEffectSkipFirstRender";
type CsvURL = string;
type TableData<T> = T[] | CsvURL;
@@ -234,12 +235,16 @@ export const LoadingDataTableComponent = memo(
const [filters, setFilters] = useState<ColumnFiltersState>([]);
// We need to clear the selection when sort, query, or filters change
- // Currently, our selection is index-based,
- // so we can't rely on the data to be the same when these change
- // We can remove this when we have a stable key for each row
+ // if we don't have a stable ID for each row, which is determined by
+ // _marimo_row_id.
+ const hasStableRowId = props.fieldTypes?.some(
+ (fieldType) => fieldType[0] === INDEX_COLUMN_NAME,
+ );
useEffectSkipFirstRender(() => {
- setValue([]);
- }, [setValue, filters, searchQuery, sorting]);
+ if (!hasStableRowId) {
+ setValue([]);
+ }
+ }, [setValue, filters, searchQuery, sorting, hasStableRowId]);
// If pageSize changes, reset pagination state
useEffect(() => {
@@ -477,26 +482,27 @@ const DataTableComponent = ({
const fieldTypesOrInferred = fieldTypes ?? inferFieldTypes(data);
const shownColumns = fieldTypesOrInferred.length;
+ const memoizedRowHeaders = useDeepCompareMemoize(rowHeaders);
+ const memoizedFieldTypes = useDeepCompareMemoize(fieldTypesOrInferred);
+ const memoizedTextJustifyColumns = useDeepCompareMemoize(textJustifyColumns);
+ const memoizedWrappedColumns = useDeepCompareMemoize(wrappedColumns);
const columns = useMemo(
() =>
generateColumns({
- rowHeaders: rowHeaders,
- selection,
- fieldTypes: fieldTypesOrInferred,
- textJustifyColumns,
- wrappedColumns,
+ rowHeaders: memoizedRowHeaders,
+ selection: selection,
+ fieldTypes: memoizedFieldTypes,
+ textJustifyColumns: memoizedTextJustifyColumns,
+ wrappedColumns: memoizedWrappedColumns,
// Only show data types if they are explicitly set
- showDataTypes: Boolean(fieldTypes),
+ showDataTypes: Boolean(memoizedFieldTypes),
}),
- /* eslint-disable react-hooks/exhaustive-deps */
[
- useDeepCompareMemoize([
- selection,
- fieldTypesOrInferred,
- rowHeaders,
- textJustifyColumns,
- wrappedColumns,
- ]),
+ selection,
+ memoizedRowHeaders,
+ memoizedFieldTypes,
+ memoizedTextJustifyColumns,
+ memoizedWrappedColumns,
],
);
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index e04287e3b1..d4854acda9 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -32,6 +32,10 @@ from marimo._plugins.ui._impl.dataframes.transforms.types import (
FilterRowsTransform,
TransformType,
)
+from marimo._plugins.ui._impl.tables.selection import (
+ INDEX_COLUMN_NAME,
+ add_selection_column,
+)
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
TableManager,
@@ -265,6 +269,9 @@ class table(
validate_no_integer_columns(data)
validate_page_size(page_size)
+ if selection is not None:
+ data = add_selection_column(data)
+
# The original data passed in
self._data = data
# Holds the original data
@@ -468,7 +475,7 @@ class table(
return ""
def _convert_value(
- self, value: Union[List[int] | List[str]]
+ self, value: Union[List[int], List[str]]
) -> Union[List[JSONType], "IntoDataFrame"]:
indices = [int(v) for v in value]
self._selected_manager = self._searched_manager.select_rows(indices)
@@ -497,6 +504,9 @@ class table(
else self._searched_manager
)
+ # Remove the selection column before downloading
+ manager = manager.drop_columns([INDEX_COLUMN_NAME])
+
ext = args.format
if ext == "csv":
return mo_data.csv(manager.to_csv()).url
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 627320f84d..48f1b0e732 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -122,22 +122,28 @@ class DefaultTableManager(TableManager[JsonTableData]):
return DefaultTableManager([self.data[i] for i in indices])
def select_columns(self, columns: List[str]) -> DefaultTableManager:
+ column_set = set(columns)
# Column major data
if isinstance(self.data, dict):
new_data: Dict[str, Any] = {
key: value
for key, value in self.data.items()
- if key in columns
+ if key in column_set
}
return DefaultTableManager(new_data)
# Row major data
return DefaultTableManager(
[
- {key: row[key] for key in columns}
+ {key: row[key] for key in column_set}
for row in self._normalize_data(self.data)
]
)
+ def drop_columns(self, columns: list[str]) -> DefaultTableManager:
+ return self.select_columns(
+ list(set(self.get_column_names()) - set(columns))
+ )
+
def take(self, count: int, offset: int) -> DefaultTableManager:
if count < 0:
raise ValueError("Count must be a positive integer")
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index 7d4df7d4ff..9c55ef6128 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -72,6 +72,11 @@ class IbisTableManagerFactory(TableManagerFactory):
) -> TableManager[ibis.Table]:
return IbisTableManager(self.data.select(columns))
+ def drop_columns(
+ self, columns: list[str]
+ ) -> TableManager[ibis.Table]:
+ return IbisTableManager(self.data.drop(columns))
+
def get_row_headers(
self,
) -> list[str]:
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index 0d3ebbd603..2051adcec5 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -13,6 +13,7 @@ from marimo._plugins.ui._impl.tables.format import (
FormatMapping,
format_value,
)
+from marimo._plugins.ui._impl.tables.selection import INDEX_COLUMN_NAME
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
@@ -88,11 +89,20 @@ class NarwhalsTableManager(
def select_rows(self, indices: list[int]) -> TableManager[Any]:
df = self.as_frame()
+ # Prefer the index column for selections
+ if INDEX_COLUMN_NAME in df.columns:
+ # Drop the index column before returning
+ return self.with_new_data(
+ df.filter(nw.col(INDEX_COLUMN_NAME).is_in(indices))
+ )
return self.with_new_data(df[indices])
def select_columns(self, columns: list[str]) -> TableManager[Any]:
return self.with_new_data(self.data.select(columns))
+ def drop_columns(self, columns: list[str]) -> TableManager[Any]:
+ return self.with_new_data(self.data.drop(columns, strict=False))
+
def get_row_headers(
self,
) -> list[str]:
@@ -138,6 +148,8 @@ class NarwhalsTableManager(
expressions: list[Any] = []
for column, dtype in self.nw_schema.items():
+ if column == INDEX_COLUMN_NAME:
+ continue
if dtype == nw.String:
expressions.append(nw.col(column).str.contains(f"(?i){query}"))
elif dtype == nw.List(nw.String):
@@ -280,10 +292,13 @@ class NarwhalsTableManager(
return None
def get_num_columns(self) -> int:
- return len(self.nw_schema.names())
+ return len(self.get_column_names())
def get_column_names(self) -> list[str]:
- return self.nw_schema.names()
+ column_names = self.nw_schema.names()
+ if INDEX_COLUMN_NAME in column_names:
+ column_names.remove(INDEX_COLUMN_NAME)
+ return column_names
def get_unique_column_values(self, column: str) -> list[str | int | float]:
try:
diff --git a/marimo/_plugins/ui/_impl/tables/selection.py b/marimo/_plugins/ui/_impl/tables/selection.py
new file mode 100644
index 0000000000..720a583b24
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/tables/selection.py
@@ -0,0 +1,26 @@
+from __future__ import annotations
+
+from typing import TypeVar, cast
+
+import narwhals.stable.v1 as nw
+from narwhals.typing import IntoDataFrame
+
+INDEX_COLUMN_NAME = "_marimo_row_id"
+
+T = TypeVar("T")
+
+
+def add_selection_column(data: T) -> T:
+ if nw.dependencies.is_into_dataframe(data):
+ df = nw.from_native(cast(IntoDataFrame, data), strict=True)
+ if INDEX_COLUMN_NAME not in df.columns:
+ return df.with_row_index(name=INDEX_COLUMN_NAME).to_native() # type: ignore[return-value]
+ return data
+
+
+def remove_selection_column(data: T) -> T:
+ if nw.dependencies.is_into_dataframe(data):
+ df = nw.from_native(cast(IntoDataFrame, data), strict=True)
+ if INDEX_COLUMN_NAME in df.columns:
+ return df.drop(INDEX_COLUMN_NAME).to_native() # type: ignore[return-value]
+ return data
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 7a6bd0a088..a25be9243f 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -64,46 +64,50 @@ class TableManager(abc.ABC, Generic[T]):
def apply_formatting(
self, format_mapping: Optional[FormatMapping]
) -> TableManager[Any]:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def supports_filters(self) -> bool:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def sort_values(
self, by: ColumnName, descending: bool
) -> TableManager[Any]:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def to_csv(
self,
format_mapping: Optional[FormatMapping] = None,
) -> bytes:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def to_json(self) -> bytes:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def select_rows(self, indices: list[int]) -> TableManager[Any]:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def select_columns(self, columns: list[str]) -> TableManager[Any]:
- raise NotImplementedError
+ pass
+
+ @abc.abstractmethod
+ def drop_columns(self, columns: list[str]) -> TableManager[Any]:
+ pass
@abc.abstractmethod
def get_row_headers(self) -> list[str]:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def get_field_type(
self, column_name: str
) -> Tuple[FieldType, ExternalDataType]:
- raise NotImplementedError
+ pass
def get_field_types(self) -> FieldTypes:
return [
@@ -113,42 +117,42 @@ class TableManager(abc.ABC, Generic[T]):
@abc.abstractmethod
def take(self, count: int, offset: int) -> TableManager[Any]:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def search(self, query: str) -> TableManager[Any]:
- raise NotImplementedError
+ pass
@staticmethod
@abc.abstractmethod
def is_type(value: Any) -> bool:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def get_summary(self, column: str) -> ColumnSummary:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def get_num_rows(self, force: bool = True) -> Optional[int]:
# This can be expensive to compute,
# so we allow optionals
- raise NotImplementedError
+ pass
@abc.abstractmethod
def get_num_columns(self) -> int:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def get_column_names(self) -> list[str]:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def get_unique_column_values(self, column: str) -> list[str | int | float]:
- raise NotImplementedError
+ pass
@abc.abstractmethod
def get_sample_values(self, column: str) -> list[Any]:
- raise NotImplementedError
+ pass
def __repr__(self) -> str:
rows = self.get_num_rows(force=False)
@@ -162,9 +166,9 @@ class TableManagerFactory(abc.ABC):
@staticmethod
@abc.abstractmethod
def package_name() -> str:
- raise NotImplementedError
+ pass
@staticmethod
@abc.abstractmethod
def create() -> type[TableManager[Any]]:
- raise NotImplementedError
+ pass
diff --git a/marimo/_smoke_tests/dataframe.py b/marimo/_smoke_tests/dataframe.py
index 5c0a9cd0ac..9801a22693 100644
--- a/marimo/_smoke_tests/dataframe.py
+++ b/marimo/_smoke_tests/dataframe.py
@@ -14,18 +14,18 @@
import marimo
-__generated_with = "0.9.10"
+__generated_with = "0.11.5"
app = marimo.App(width="full")
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""# 🤖 Lists/Dicts""")
return
@app.cell
-def __(mo):
+def _(mo):
_data = [
{"Name": "John", "Age": 30, "City": "New York"},
{"Name": "Alice", "Age": 24, "City": "San Francisco"},
@@ -36,13 +36,13 @@ def __(mo):
@app.cell
-def __(as_list):
+def _(as_list):
as_list.value
return
@app.cell
-def __(mo):
+def _(mo):
_data = {
"Name": ["John", "Alice"],
"Age": [30, 24],
@@ -54,13 +54,13 @@ def __(mo):
@app.cell
-def __(as_dict):
+def _(as_dict):
as_dict.value
return
@app.cell
-def __(mo):
+def _(mo):
_data = [1, 2, "hello", False]
as_primitives = mo.ui.table(_data)
as_primitives
@@ -68,168 +68,175 @@ def __(mo):
@app.cell
-def __(as_primitives):
+def _(as_primitives):
as_primitives.value
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""# 🐼 Pandas""")
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## mo.ui.dataframe""")
return
@app.cell
-def __(cars, mo):
+def _(cars, mo):
dataframe = mo.ui.dataframe(cars)
dataframe
return (dataframe,)
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## mo.ui.table""")
return
@app.cell
-def __(dataframe, mo):
- mo.ui.table(dataframe.value, selection=None)
+def _(dataframe, mo):
+ t = mo.ui.table(dataframe.value)
+ t
+ return (t,)
+
+
+def _(t):
+ t.value
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## .value""")
return
@app.cell
-def __(dataframe):
+def _(dataframe):
dataframe.value
return
@app.cell
-def __(dataframe):
+def _(dataframe):
dataframe.value["Cylinders"]
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## mo.ui.data_explorer""")
return
@app.cell
-def __(mo, pl_dataframe):
+def _(mo, pl_dataframe):
mo.ui.data_explorer(pl_dataframe)
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""# 🐻‍❄️ Polars""")
return
@app.cell
-def __(mo):
+def _(mo):
mo.md("""## mo.ui.dataframe""")
return
@app.cell
-def __(mo, pl_dataframe):
+def _(mo, pl_dataframe):
pl_dataframe_prime = mo.ui.dataframe(pl_dataframe)
pl_dataframe_prime
return (pl_dataframe_prime,)
@app.cell
-def __(pl_dataframe_prime):
+def _(pl_dataframe_prime):
pl_dataframe_prime.value
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## mo.ui.table""")
return
@app.cell
-def __(cars, mo, pl):
+def _(cars, mo, pl):
pl_dataframe = pl.DataFrame(cars)
mo.ui.table(pl_dataframe, selection=None)
return (pl_dataframe,)
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## mo.ui.data_explorer""")
return
@app.cell
-def __(mo, pl_dataframe):
+def _(mo, pl_dataframe):
mo.ui.data_explorer(pl_dataframe)
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""# 🏹 Arrow""")
return
@app.cell
-def __(cars, mo, pa):
+def _(cars, mo, pa):
arrow_table = pa.Table.from_pandas(cars)
mo.accordion({"Details": mo.plain_text(arrow_table)})
return (arrow_table,)
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## mo.ui.table""")
return
@app.cell
-def __(arrow_table, mo):
+def _(arrow_table, mo):
arrow_table_el = mo.ui.table(arrow_table)
arrow_table_el
return (arrow_table_el,)
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md("""## .value""")
return
@app.cell
-def __(arrow_table_el):
+def _(arrow_table_el):
arrow_table_el.value
return
@app.cell
-def __(arrow_table, mo):
+def _(arrow_table, mo):
mo.ui.data_explorer(arrow_table)
return
@app.cell
-def __(mo):
+def _(mo):
mo.md(
rf"""
# 💽 Dataframe protocol
@@ -240,7 +247,7 @@ def __(mo):
@app.cell
-def __():
+def _():
import dask.dataframe as dd
import requests
@@ -252,7 +259,7 @@ def __():
@app.cell
-def __():
+def _():
import ibis
ibis.options.interactive = True
@@ -266,38 +273,44 @@ def __():
@app.cell
-def __(mo):
+def _(mo):
mo.md(rf"## mo.ui.table")
return
@app.cell
-def __(ibis_data, mo):
+def _(ibis_penguins):
+ ibis_penguins.value
+ return
+
+
+def _(ibis_data, mo):
ibis_penguins = mo.ui.table(ibis_data)
ibis_penguins
return (ibis_penguins,)
@app.cell
-def __(ibis_penguins):
+def _(ibis_penguins):
ibis_penguins.value
return
@app.cell(hide_code=True)
-def __(mo):
+def _(mo):
mo.md(rf"## mo.ui.data_explorer")
return
@app.cell
-def __(ibis_data, mo):
+def _(ibis_data, mo):
mo.ui.data_explorer(ibis_data)
return
@app.cell
-def __():
+def _():
import marimo as mo
import pandas as pd
import polars as pl
@@ -310,7 +323,7 @@ def __():
@app.cell
-def __(cars, mo):
+def _(cars, mo):
_df = mo.sql(
f"""
SELECT * FROM cars WHERE Cylinders > 6;
diff --git a/marimo/_smoke_tests/dataframes/dicts_vs_dfs.py b/marimo/_smoke_tests/dataframes/dicts_vs_dfs.py
index 35bb627007..055e71c550 100644
--- a/marimo/_smoke_tests/dataframes/dicts_vs_dfs.py
+++ b/marimo/_smoke_tests/dataframes/dicts_vs_dfs.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.11.2"
+__generated_with = "0.11.5"
app = marimo.App(width="medium")
@@ -32,13 +32,27 @@ def _(pl):
@app.cell
def _(mo, test_df):
- mo.ui.table(test_df)
+ t1 = mo.ui.table(test_df)
+ t1
+ return (t1,)
+
+
+def _(t1):
+ t1.value
return
@app.cell
def _(mo, pd, test_df):
- mo.ui.table(pd.DataFrame(test_df.to_dicts()))
+ t2 = mo.ui.table(pd.DataFrame(test_df.to_dicts()))
+ t2
+ return (t2,)
+
+
+def _(t2):
+ t2.value
return
diff --git a/marimo/_smoke_tests/tables/booleans.py b/marimo/_smoke_tests/tables/booleans.py
index 1f6c173d41..bb4eaa3c6a 100644
--- a/marimo/_smoke_tests/tables/booleans.py
+++ b/marimo/_smoke_tests/tables/booleans.py
@@ -9,12 +9,12 @@
import marimo
-__generated_with = "0.8.14"
+__generated_with = "0.11.5"
app = marimo.App(width="medium")
@app.cell
-def __():
+def _():
import marimo as mo
import pandas as pd
import polars as pl
@@ -22,7 +22,7 @@ def __():
@app.cell
-def __(pd):
+def _(pd):
data = {
"A": [True, True, True],
"B": [False, False, False],
@@ -30,18 +30,25 @@ def __(pd):
}
pd.DataFrame(data)
- return data,
+ return (data,)
@app.cell
-def __(data, pl):
+def _(data, pl):
pl.DataFrame(data)
return
@app.cell
-def __(data, mo):
- mo.ui.table(data)
+def _(data, mo):
+ t = mo.ui.table(data)
+ t
+ return (t,)
+
+
+def _(t):
+ t.value
return
diff --git a/marimo/_smoke_tests/tables/complex_types.py b/marimo/_smoke_tests/tables/complex_types.py
index d868c938fc..18f0689bed 100644
--- a/marimo/_smoke_tests/tables/complex_types.py
+++ b/marimo/_smoke_tests/tables/complex_types.py
@@ -1,11 +1,11 @@
import marimo
-__generated_with = "0.9.14"
+__generated_with = "0.11.5"
app = marimo.App(width="medium")
@app.cell(hide_code=True)
-def __():
+def _():
import polars as pl
from datetime import datetime, date, time
import marimo as mo
@@ -69,27 +69,27 @@ def __():
@app.cell
-def __(df):
+def _(df):
pandas = df.to_pandas()
pandas
return (pandas,)
@app.cell
-def __(df):
- arrow = df.to_arrow()
- arrow
- return (arrow,)
+def _():
+ # arrow = df.to_arrow()
+ # arrow
+ return
@app.cell
-def __(df, mo):
+def _(df, mo):
mo.ui.dataframe(df)
return
@app.cell
-def __(mo):
+def _(mo):
import pandas as pd
pandas_with_timestamp = pd.DataFrame(
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index d515b28713..bfd2702c92 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -48,6 +48,18 @@ class TestDefaultTable(unittest.TestCase):
]
assert selected_manager.data == expected_data
+ def test_drop_columns(self) -> None:
+ columns = ["name"]
+ dropped_manager = self.manager.drop_columns(columns)
+ expected_data = [
+ {"age": 30, "birth_year": date(1994, 5, 24)},
+ {"age": 25, "birth_year": date(1999, 7, 14)},
+ {"age": 35, "birth_year": date(1989, 12, 1)},
+ {"age": 28, "birth_year": date(1996, 3, 5)},
+ {"age": 22, "birth_year": date(2002, 1, 30)},
+ ]
+ assert dropped_manager.data == expected_data
+
def test_get_row_headers(self) -> None:
expected_headers = []
assert self.manager.get_row_headers() == expected_headers
@@ -322,6 +334,14 @@ class TestColumnarDefaultTable(unittest.TestCase):
}
assert selected_manager.data == expected_data
+ def test_drop_columns(self) -> None:
+ columns = ["name", "birth_year"]
+ dropped_manager = self.manager.drop_columns(columns)
+ expected_data = {
+ "age": [30, 25, 35, 28, 22],
+ }
+ assert dropped_manager.data == expected_data
+
def test_get_row_headers(self) -> None:
expected_headers = []
assert self.manager.get_row_headers() == expected_headers
@@ -586,6 +606,10 @@ class TestDictionaryDefaultTable(unittest.TestCase):
selected_manager = self.manager.select_columns(["a"])
assert selected_manager.data == {"a": 1}
+ def test_drop_columns(self) -> None:
+ dropped_manager = self.manager.drop_columns(["a"])
+ assert dropped_manager.data == {"b": 2}
+
def test_get_rows_headers(self) -> None:
headers = self.manager.get_row_headers()
assert headers == []
diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
index 7a395798a5..d0477eb03f 100644
--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
@@ -112,6 +112,14 @@ class TestIbisTableManagerFactory(unittest.TestCase):
expected_data.to_pandas()
)
+ def test_drop_columns(self) -> None:
+ columns = ["A"]
+ dropped_manager = self.manager.drop_columns(columns)
+ expected_data = self.data.drop(columns)
+ assert dropped_manager.data.to_pandas().equals(
+ expected_data.to_pandas()
+ )
+
def test_get_row_headers(self) -> None:
expected_headers = []
assert self.manager.get_row_headers() == expected_headers
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index 178edeaab3..4959a0baa3 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -176,6 +176,12 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):
expected_data = self.data.select(columns)
assert_frame_equal(selected_manager.data, expected_data)
+ def test_drop_columns(self) -> None:
+ columns = ["A"]
+ dropped_manager = self.manager.drop_columns(columns)
+ expected_data = self.data.drop(columns)
+ assert_frame_equal(dropped_manager.data, expected_data)
+
def test_get_row_headers(self) -> None:
expected_headers = []
assert self.manager.get_row_headers() == expected_headers
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index a2723e8c02..72d6c9cd13 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -182,6 +182,12 @@ class TestPandasTableManager(unittest.TestCase):
expected_data = self.data[columns]
assert_frame_equal(selected_manager.data, expected_data)
+ def test_drop_columns(self) -> None:
+ columns = ["C"]
+ dropped_manager = self.manager.drop_columns(columns)
+ expected_data = self.data.drop(columns, axis=1)
+ assert_frame_equal(dropped_manager.data, expected_data)
+
def test_get_row_headers(self) -> None:
expected_headers = []
assert self.manager.get_row_headers() == expected_headers
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 7823351f22..e44fe026f4 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -184,6 +184,12 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
expected_data = self.data.select(columns)
assert assert_frame_equal(selected_manager.data, expected_data)
+ def test_drop_columns(self) -> None:
+ columns = ["A"]
+ dropped_manager = self.manager.drop_columns(columns)
+ expected_data = self.data.drop(columns)
+ assert assert_frame_equal(dropped_manager.data, expected_data)
+
def test_get_row_headers(self) -> None:
expected_headers = []
assert self.manager.get_row_headers() == expected_headers
diff --git a/tests/_plugins/ui/_impl/tables/test_selection.py b/tests/_plugins/ui/_impl/tables/test_selection.py
new file mode 100644
index 0000000000..aa76b367a9
--- /dev/null
+++ b/tests/_plugins/ui/_impl/tables/test_selection.py
@@ -0,0 +1,209 @@
+from __future__ import annotations
+
+from typing import Any
+
+import narwhals.stable.v1 as nw
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManager
+from marimo._plugins.ui._impl.tables.selection import (
+ INDEX_COLUMN_NAME,
+ add_selection_column,
+ remove_selection_column,
+)
+
+try:
+ import pandas as pd
+ import polars as pl
+ import pyarrow as pa
+except ImportError:
+ pl = None
+ pd = None
+ pa = None
+
+BACKENDS = [pl, pd, pa]
+
+HAS_DEPS = (
+ DependencyManager.polars.has()
+ and DependencyManager.pandas.has()
+ and DependencyManager.pyarrow.has()
+)
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_selection_with_index_column(backend: Any):
+ # Create test data with index column
+ data = nw.from_dict(
+ {
+ INDEX_COLUMN_NAME: [0, 1, 2],
+ "name": ["Alice", "Bob", "Charlie"],
+ "age": [30, 25, 35],
+ },
+ native_namespace=backend,
+ )
+ manager = NarwhalsTableManager(data)
+
+ # Test selection using index column
+ selected = manager.select_rows([0, 2])
+ result = selected.data.to_dict(as_series=False)
+ assert result[INDEX_COLUMN_NAME] == [0, 2]
+ assert result["name"] == ["Alice", "Charlie"]
+ assert result["age"] == [30, 35]
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_selection_with_index_column_and_sort(backend: Any):
+ # Create test data with index column
+ data = nw.from_dict(
+ {
+ INDEX_COLUMN_NAME: [0, 1, 2],
+ "name": ["Alice", "Bob", "Charlie"],
+ "age": [30, 25, 35],
+ },
+ native_namespace=backend,
+ )
+ manager = NarwhalsTableManager(data)
+
+ # Sort and select
+ sorted_data = manager.sort_values(by="age", descending=True)
+ selected = sorted_data.select_rows([0, 2])
+ result = selected.data.to_dict(as_series=False)
+ assert result[INDEX_COLUMN_NAME] == [2, 0] # Original indices preserved
+ assert result["name"] == ["Charlie", "Alice"]
+ assert result["age"] == [35, 30]
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_selection_with_index_column_and_search(backend: Any):
+ # Create test data with index column
+ data = nw.from_dict(
+ {
+ INDEX_COLUMN_NAME: [0, 1, 2],
+ "name": ["Alice", "Bob", "Charlie"],
+ "age": [30, 25, 35],
+ },
+ native_namespace=backend,
+ )
+ manager = NarwhalsTableManager(data)
+
+ # Search and select
+ searched = manager.search("ali")
+ selected = searched.select_rows([0])
+ result = selected.data.to_dict(as_series=False)
+ assert result[INDEX_COLUMN_NAME] == [0]
+ assert result["name"] == ["Alice"]
+ assert result["age"] == [30]
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_selection_with_index_column_empty(backend: Any):
+ # Create test data with index column
+ data = nw.from_dict(
+ {INDEX_COLUMN_NAME: [0, 1], "name": ["Alice", "Bob"], "age": [30, 25]},
+ native_namespace=backend,
+ )
+ manager = NarwhalsTableManager(data)
+
+ # Test empty selection
+ selected = manager.select_rows([])
+ result = selected.data.to_dict(as_series=False)
+ assert result[INDEX_COLUMN_NAME] == []
+ assert result["name"] == []
+ assert result["age"] == []
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_selection_without_index_column(backend: Any):
+ # Create test data without index column
+ data = nw.from_dict(
+ {"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},
+ native_namespace=backend,
+ )
+ manager = NarwhalsTableManager(data)
+
+ # Test selection falls back to positional indexing
+ selected = manager.select_rows([0, 2])
+ result = selected.data.to_dict(as_series=False)
+ assert "name" in result
+ assert result["name"] == ["Alice", "Charlie"]
+ assert result["age"] == [30, 35]
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_selection_with_index_column_take(backend: Any):
+ # Create test data with index column
+ data = nw.from_dict(
+ {
+ INDEX_COLUMN_NAME: [0, 1, 2, 3, 4],
+ "name": ["Alice", "Bob", "Charlie", "Dave", "Eve"],
+ "age": [30, 25, 35, 28, 22],
+ },
+ native_namespace=backend,
+ )
+ manager = NarwhalsTableManager(data)
+
+ # Test take operation preserves index column
+ taken = manager.take(2, 1) # Take 2 rows starting from index 1
+ result = taken.data.to_dict(as_series=False)
+ assert result[INDEX_COLUMN_NAME] == [1, 2]
+ assert result["name"] == ["Bob", "Charlie"]
+ assert result["age"] == [25, 35]
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_add_selection_to_dataframe(backend: Any):
+ data = nw.from_dict(
+ {"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},
+ native_namespace=backend,
+ )
+ with_selection = add_selection_column(data.to_native())
+
+ # Convert back to Narwhals to assert
+ nw_df = nw.from_native(with_selection)
+ assert nw_df.columns == [INDEX_COLUMN_NAME, "name", "age"]
+ assert nw_df[INDEX_COLUMN_NAME].to_list() == [0, 1, 2]
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_add_selection_to_dataframe_already_has_index(backend: Any):
+ data = nw.from_dict(
+ {
+ INDEX_COLUMN_NAME: [0, 1, 2],
+ "name": ["Alice", "Bob", "Charlie"],
+ "age": [30, 25, 35],
+ },
+ native_namespace=backend,
+ )
+ with_selection = add_selection_column(data.to_native())
+
+ # Convert back to Narwhals to assert
+ nw_df = nw.from_native(with_selection)
+ assert nw_df.columns == [INDEX_COLUMN_NAME, "name", "age"]
+ assert nw_df[INDEX_COLUMN_NAME].to_list() == [0, 1, 2]
+
+
[email protected](not HAS_DEPS, reason="Deps not installed")
[email protected]("backend", BACKENDS)
+def test_remove_selection_column(backend: Any):
+ data = nw.from_dict(
+ {"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},
+ native_namespace=backend,
+ )
+ with_selection = add_selection_column(data.to_native())
+ without_selection = remove_selection_column(with_selection)
+ nw_df = nw.from_native(without_selection)
+ assert nw_df.columns == ["name", "age"]
+
+ # Remove again
+ without_selection = remove_selection_column(without_selection)
+ nw_df = nw.from_native(without_selection)
+ assert nw_df.columns == ["name", "age"]
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index a19763644e..c4de494692 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -291,7 +291,7 @@ def test_value_with_sorting_then_selection_dfs(df: Any) -> None:
)
value = table._convert_value(["0"])
assert not isinstance(value, nw.DataFrame)
- assert nw.from_native(value)["a"][0] == "z"
+ assert nw.from_native(value)["a"][0] == "x"
table._search(
SearchTableArgs(
@@ -358,7 +358,7 @@ def test_value_with_search_then_selection_dfs(df: Any) -> None:
page_number=0,
)
)
- value = table._convert_value(["0"])
+ value = table._convert_value(["1"])
assert not isinstance(value, nw.DataFrame)
assert nw.from_native(value)["a"][0] == "bar"
@@ -385,6 +385,44 @@ def test_value_with_search_then_selection_dfs(df: Any) -> None:
assert nw.from_native(value)["a"][0] == "baz"
+def test_value_with_selection_then_sorting_dict_of_lists() -> None:
+ data = {
+ "company": [
+ "Company A",
+ "Company B",
+ "Company C",
+ "Company D",
+ "Company E",
+ ],
+ "type": ["Tech", "Finance", "Health", "Tech", "Finance"],
+ "net_worth": [1000, 2000, 1500, 1800, 1700],
+ }
+ table = ui.table(data)
+
+ table._search(
+ SearchTableArgs(
+ page_size=10,
+ page_number=0,
+ )
+ )
+ assert table._convert_value(["0", "2"])["company"] == [
+ "Company A",
+ "Company C",
+ ]
+
+ table._search(
+ SearchTableArgs(
+ sort=SortArgs("net_worth", descending=True),
+ page_size=10,
+ page_number=0,
+ )
+ )
+ assert table._convert_value(["0", "2"])["company"] == [
+ "Company B",
+ "Company E",
+ ]
+
+
def test_search_sort_nonexistent_columns() -> None:
data = ["banana", "apple", "cherry", "date", "elderberry"]
table = ui.table(data)
@@ -929,7 +967,8 @@ def test_column_clamping_with_polars():
assert table._component_args["total-columns"] == 60
csv = from_data_uri(table._component_args["data"])[1].decode("utf-8")
headers = csv.split("\n")[0].split(",")
- assert len(headers) == 60 # 60 columns
+
+ assert len(headers) == 61 # 60 columns + 1 selection column
assert len(table._component_args["field-types"]) == 60