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: dataframe be sorting follow-ups (#1605)

Myles Scolnick09ec94b61252
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index df1eb419f4..d8dbea8553 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -1,11 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Column, sortingFns } from "@tanstack/react-table";
+import { Column } from "@tanstack/react-table";
import {
ChevronsUpDown,
ArrowDownNarrowWideIcon,
ArrowDownWideNarrowIcon,
- ArrowDown10Icon,
- ArrowDown01Icon,
CopyIcon,
} from "lucide-react";
@@ -33,11 +31,8 @@ export const DataTableColumnHeader = <TData, TValue>({
return <div className={cn(className)}>{header}</div>;
}
- const sortFn = column.getSortingFn();
- const AscIcon =
- sortFn === sortingFns.basic ? ArrowDown01Icon : ArrowDownNarrowWideIcon;
- const DescIcon =
- sortFn === sortingFns.basic ? ArrowDown10Icon : ArrowDownWideNarrowIcon;
+ const AscIcon = ArrowDownNarrowWideIcon;
+ const DescIcon = ArrowDownWideNarrowIcon;
return (
<DropdownMenu modal={false}>
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index cff4704cde..8803bc0600 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -25,6 +25,9 @@ import { DelayMount } from "@/components/utils/delay-mount";
import { ColumnHeaderSummary } from "@/components/data-table/types";
import { OnChangeFn, SortingState } from "@tanstack/react-table";
+type CsvURL = string;
+type TableData<T> = T[] | CsvURL;
+
/**
* Arguments for a data table
*
@@ -33,7 +36,7 @@ import { OnChangeFn, SortingState } from "@tanstack/react-table";
*/
interface Data<T> {
label: string | null;
- data: T[] | string;
+ data: TableData<T>;
hasMore: boolean;
totalRows: number;
pagination: boolean;
@@ -51,10 +54,10 @@ type Functions = {
get_column_summaries: (opts: {}) => Promise<{
summaries: ColumnHeaderSummary[];
}>;
- sort_values: (req: {
+ sort_values: <T>(req: {
by: string | null;
descending: boolean;
- }) => Promise<object[] | string>;
+ }) => Promise<TableData<T>>;
};
type S = Array<string | number>;
@@ -108,64 +111,66 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
<LoadingDataTableComponent
{...props.data}
{...props.functions}
- data={props.data.data as string | (string & unknown[])}
+ data={props.data.data}
value={props.value}
setValue={props.setValue}
/>
);
});
-interface DataTableProps extends Data<unknown>, Functions {
+interface DataTableProps<T> extends Data<T>, Functions {
className?: string;
value: S;
setValue: (value: S) => void;
- sorting?: SortingState;
+ sorting: SortingState;
setSorting?: OnChangeFn<SortingState>;
}
export const LoadingDataTableComponent = memo(
- (props: DataTableProps & { data: string | (string & unknown[]) }) => {
- const isDirectRender = typeof props.data !== "string";
-
- const initialData = props.data;
+ <T extends {}>(
+ props: Omit<DataTableProps<T>, "sorting"> & { data: TableData<T> },
+ ) => {
const sortValues = props.sort_values;
- const rowHeaders = props.rowHeaders;
-
const [sorting, setSorting] = useState<SortingState>([]);
- const [tableData, setTableData] = useState(initialData);
- useEffect(() => {
- const getSortedData = async () => {
- if (sorting.length === 0) {
- setTableData(initialData);
- return;
- }
+ const { data, loading, error } = useAsyncData<T[]>(async () => {
+ // If there is no data, return an empty array
+ if (props.totalRows === 0) {
+ return [];
+ }
+
+ // Table data is a url string or an array of objects
+ let tableData = props.data;
- const sortedData = await sortValues({
+ // If we have sort configuration, fetch the sorted data
+ if (sorting.length > 0) {
+ if (sorting.length > 1) {
+ Logger.warn("Multiple sort columns are not supported");
+ }
+ const sortedData = await sortValues<T>({
by: sorting[0].id,
descending: sorting[0].desc,
});
- setTableData(sortedData as string | (string & unknown[]));
- };
-
- getSortedData();
- }, [sorting, sortValues, initialData, rowHeaders.length]);
+ tableData = sortedData;
+ }
- const { data, loading, error } = useAsyncData<unknown[]>(() => {
- if (!tableData || props.totalRows === 0 || isDirectRender) {
- return Promise.resolve([]);
+ // If we already have the data, return it
+ if (Array.isArray(tableData)) {
+ return tableData;
}
+
+ // Otherwise, load the data from the URL
return vegaLoadData(
tableData,
{ type: "csv", parse: getVegaFieldTypes(props.fieldTypes) },
{ handleBigInt: true },
);
- }, [tableData, props.fieldTypes, props.totalRows]);
+ }, [sorting, sortValues, props.fieldTypes, props.data]);
const { data: columnSummaries, error: columnSummariesError } =
useAsyncData(() => {
- if (isDirectRender || props.totalRows === 0) {
+ if (props.totalRows === 0) {
return Promise.resolve({ summaries: [] });
}
return props.get_column_summaries({});
@@ -185,9 +190,10 @@ export const LoadingDataTableComponent = memo(
);
}
+ let errorComponent: React.ReactNode = null;
if (error) {
- return (
- <Alert variant="destructive">
+ errorComponent = (
+ <Alert variant="destructive" className="mb-2">
<AlertTitle>Error</AlertTitle>
<div className="text-md">
{error.message || "An unknown error occurred"}
@@ -196,27 +202,17 @@ export const LoadingDataTableComponent = memo(
);
}
- if (typeof props.data !== "string") {
- return (
+ return (
+ <>
+ {errorComponent}
<DataTableComponent
{...props}
- data={tableData as unknown[] | (string & unknown[])}
- value={props.value}
- setValue={props.setValue}
+ data={data || Arrays.EMPTY}
+ columnSummaries={columnSummaries?.summaries}
sorting={sorting}
setSorting={setSorting}
/>
- );
- }
-
- return (
- <DataTableComponent
- {...props}
- data={data || Arrays.EMPTY}
- columnSummaries={columnSummaries?.summaries}
- sorting={sorting}
- setSorting={setSorting}
- />
+ </>
);
},
);
@@ -242,7 +238,7 @@ const DataTableComponent = ({
setValue,
sorting,
setSorting,
-}: DataTableProps & {
+}: DataTableProps<unknown> & {
data: unknown[];
columnSummaries?: ColumnHeaderSummary[];
}): JSX.Element => {
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 2b24b750b8..90014d8c2e 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -42,10 +42,10 @@ type PluginFunctions = {
values: unknown[];
too_many_values: boolean;
}>;
- sort_values: (req: {
+ sort_values: <T>(req: {
by: string | null;
descending: boolean;
- }) => Promise<object[] | string>;
+ }) => Promise<T[] | string>;
};
// Value is selection, but it is not currently exposed to the user
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index 8f0f73b119..352a0234d8 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -86,14 +86,14 @@ export const vegaLoader = createLoader();
*
* This resolves to an array of objects, where each object represents a row.
*/
-export function vegaLoadData(
+export function vegaLoadData<T = object>(
url: string,
format: DataFormat | undefined | { type: "csv"; parse: "auto" },
opts: {
handleBigInt?: boolean;
replacePeriod?: boolean;
} = {},
-): Promise<object[]> {
+): Promise<T[]> {
const { handleBigInt = false, replacePeriod = false } = opts;
const isCsv = format?.type === "csv";
@@ -134,7 +134,7 @@ export function vegaLoadData(
disableBigInt();
}
- return results;
+ return results as T[];
});
}
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 088952ba90..dcb43aaaaf 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -21,6 +21,7 @@ from marimo._plugins.ui._impl.dataframes.transforms import Transformations
from marimo._plugins.ui._impl.tables.pandas_table import (
PandasTableManagerFactory,
)
+from marimo._plugins.ui._impl.tables.table_manager import ColumnName
if TYPE_CHECKING:
import pandas as pd
@@ -55,7 +56,7 @@ class GetColumnValuesResponse:
@dataclass
class SortValuesArgs:
- by: str
+ by: ColumnName
descending: bool
@@ -103,6 +104,10 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
_name: Final[str] = "marimo-dataframe"
+ # Only get the first 100 (for performance reasons)
+ # Could make this configurable in the arguments later if desired.
+ DISPLAY_LIMIT = 100
+
def __init__(
self,
df: pd.DataFrame,
@@ -173,20 +178,18 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
return [[name, dtype] for name, dtype in self._data.dtypes.items()] # type: ignore
def get_dataframe(self, _args: EmptyArgs) -> GetDataFrameResponse:
- # Only get the first 100 (for performance reasons)
- # Could make this configurable in the arguments later if desired.
- LIMIT = 100
-
if self._error is not None:
raise GetDataFrameError(self._error)
- manager = PandasTableManagerFactory.create()(self._value.head(LIMIT))
+ manager = PandasTableManagerFactory.create()(
+ self._value.head(self.DISPLAY_LIMIT)
+ )
url = mo_data.csv(manager.to_csv()).url
total_rows = len(self._value)
return GetDataFrameResponse(
url=url,
total_rows=total_rows,
- has_more=total_rows > LIMIT,
+ has_more=total_rows > self.DISPLAY_LIMIT,
row_headers=manager.get_row_headers(),
)
@@ -230,9 +233,8 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
return self._data
def sort_values(self, args: SortValuesArgs) -> Union[JSONType, str]:
- LIMIT = 100
return (
self._manager.sort_values(args.by, args.descending)
- .limit(LIMIT)
+ .limit(self.DISPLAY_LIMIT)
.to_data()
)
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 760c3af730..d60fd887d1 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -22,6 +22,7 @@ from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._plugins.ui._impl.tables.table_manager import (
+ ColumnName,
TableManager,
)
from marimo._plugins.ui._impl.tables.utils import get_table_manager
@@ -63,7 +64,7 @@ class ColumnSummaries:
@dataclass
class SortValuesArgs:
- by: str
+ by: ColumnName
descending: bool
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 3233535e38..e93c006fb7 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -23,7 +23,10 @@ from marimo._plugins.ui._impl.tables.polars_table import (
from marimo._plugins.ui._impl.tables.pyarrow_table import (
PyArrowTableManagerFactory,
)
-from marimo._plugins.ui._impl.tables.table_manager import TableManager
+from marimo._plugins.ui._impl.tables.table_manager import (
+ ColumnName,
+ TableManager,
+)
JsonTableData = Union[
Sequence[Union[str, int, float, bool, MIME, None]],
@@ -141,9 +144,17 @@ class DefaultTableManager(TableManager[JsonTableData]):
return list(first.keys())
return ["value"]
- def sort_values(self, by: str, descending: bool) -> DefaultTableManager:
+ def sort_values(
+ self, by: ColumnName, descending: bool
+ ) -> DefaultTableManager:
normalized = self._normalize_data(self.data)
- data = sorted(normalized, key=lambda x: x[by], reverse=descending)
+ try:
+ data = sorted(normalized, key=lambda x: x[by], reverse=descending)
+ except TypeError:
+ # Handle when all values are not comparable
+ data = sorted(
+ normalized, key=lambda x: str(x[by]), reverse=descending
+ )
return DefaultTableManager(data)
@staticmethod
diff --git a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
index 651d7ce05a..7dafef57ff 100644
--- a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
+++ b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
@@ -13,6 +13,7 @@ from marimo._plugins.ui._impl.tables.pyarrow_table import (
PyArrowTableManagerFactory,
)
from marimo._plugins.ui._impl.tables.table_manager import (
+ ColumnName,
FieldType,
FieldTypes,
TableManager,
@@ -103,6 +104,11 @@ class DataFrameProtocolTableManager(TableManager[DataFrameLike]):
def get_column_names(self) -> list[str]:
return list(self._df.column_names())
+ def sort_values(
+ self, by: ColumnName, descending: bool
+ ) -> TableManager[DataFrameLike]:
+ return self._ensure_delegate().sort_values(by, descending)
+
@staticmethod
def _get_field_type(column: Column) -> FieldType:
kind = column.dtype[0]
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 3fb0e5bddc..97d50a5f5a 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -5,6 +5,7 @@ from typing import Any
from marimo._data.models import ColumnSummary
from marimo._plugins.ui._impl.tables.table_manager import (
+ ColumnName,
FieldType,
FieldTypes,
TableManager,
@@ -226,7 +227,7 @@ class PandasTableManagerFactory(TableManagerFactory):
return self.data.columns.tolist()
def sort_values(
- self, by: str, descending: bool
+ self, by: ColumnName, descending: bool
) -> PandasTableManager:
sorted_data = self.data.sort_values(
by, ascending=not descending
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index a760558c34..a11bb1a774 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -5,6 +5,7 @@ from typing import Any, cast
from marimo._data.models import ColumnSummary, NonNestedLiteral
from marimo._plugins.ui._impl.tables.table_manager import (
+ ColumnName,
FieldType,
FieldTypes,
TableManager,
@@ -120,7 +121,7 @@ class PolarsTableManagerFactory(TableManagerFactory):
return self.data.columns
def sort_values(
- self, by: str, descending: bool
+ self, by: ColumnName, descending: bool
) -> PolarsTableManager:
sorted_data = self.data.sort(by, descending=descending)
return PolarsTableManager(sorted_data)
diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
index e4f7dd2fc4..81c5fd9c51 100644
--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
@@ -2,10 +2,11 @@
from __future__ import annotations
import io
-from typing import Any, Literal, Union, cast
+from typing import Any, Union, cast
from marimo._data.models import ColumnSummary
from marimo._plugins.ui._impl.tables.table_manager import (
+ ColumnName,
FieldType,
FieldTypes,
TableManager,
@@ -155,12 +156,11 @@ class PyArrowTableManagerFactory(TableManagerFactory):
return self.data.schema.names
def sort_values(
- self, by: str, descending: bool
+ self, by: ColumnName, descending: bool
) -> PyArrowTableManager:
- ascending: Literal["ascending", "descending"] = (
- "ascending" if not descending else "descending"
+ sorted_data = self.data.sort_by( # type: ignore
+ [(by, "ascending" if not descending else "descending")]
)
- sorted_data = self.data.sort_by([(by, ascending)]) # type: ignore
return PyArrowTableManager(sorted_data)
@staticmethod
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 14c542b161..78a976a004 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -10,9 +10,9 @@ from marimo._plugins.core.web_component import JSONType
T = TypeVar("T")
-
+ColumnName = str
FieldType = DataType
-FieldTypes = Dict[str, FieldType]
+FieldTypes = Dict[ColumnName, FieldType]
class TableManager(abc.ABC, Generic[T]):
@@ -40,7 +40,10 @@ class TableManager(abc.ABC, Generic[T]):
def supports_altair(self) -> bool:
return True
- def sort_values(self, by: str, descending: bool) -> TableManager[T]:
+ @abc.abstractmethod
+ def sort_values(
+ self, by: ColumnName, descending: bool
+ ) -> TableManager[Any]:
raise NotImplementedError
@abc.abstractmethod
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index b9990f00bf..c88daf3610 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -68,6 +68,48 @@ class TestDefaultTable(unittest.TestCase):
{"name": "Alice", "age": 30, "birth_year": date(1994, 5, 24)},
]
assert sorted_data == expected_data
+ # reverse sort
+ sorted_data = self.manager.sort_values(
+ by="name", descending=False
+ ).data
+ expected_data = [
+ {"name": "Alice", "age": 30, "birth_year": date(1994, 5, 24)},
+ {"name": "Bob", "age": 25, "birth_year": date(1999, 7, 14)},
+ {"name": "Charlie", "age": 35, "birth_year": date(1989, 12, 1)},
+ {"name": "Dave", "age": 28, "birth_year": date(1996, 3, 5)},
+ {"name": "Eve", "age": 22, "birth_year": date(2002, 1, 30)},
+ ]
+ assert sorted_data == expected_data
+
+ def test_sort_single_values(self) -> None:
+ manager = DefaultTableManager([1, 3, 2])
+ sorted_data = manager.sort_values(by="value", descending=True).data
+ expected_data = [{"value": 3}, {"value": 2}, {"value": 1}]
+ assert sorted_data == expected_data
+ # reverse sort
+ sorted_data = manager.sort_values(by="value", descending=False).data
+ expected_data = [{"value": 1}, {"value": 2}, {"value": 3}]
+ assert sorted_data == expected_data
+
+ def test_mixed_values(self) -> None:
+ manager = DefaultTableManager([1, "foo", 2, False])
+ sorted_data = manager.sort_values(by="value", descending=True).data
+ expected_data = [
+ {"value": "foo"},
+ {"value": False},
+ {"value": 2},
+ {"value": 1},
+ ]
+ assert sorted_data == expected_data
+ # reverse sort
+ sorted_data = manager.sort_values(by="value", descending=False).data
+ expected_data = [
+ {"value": 1},
+ {"value": 2},
+ {"value": False},
+ {"value": "foo"},
+ ]
+ assert sorted_data == expected_data
class TestColumnarDefaultTable(unittest.TestCase):