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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: cleanup row headers logic, so its included in sorts (#1691)
Myles Scolnick059f785661b8
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsxindex b3da34ca02..30b4004601 100644--- a/frontend/src/components/data-table/column-header.tsx+++ b/frontend/src/components/data-table/column-header.tsx@@ -41,6 +41,10 @@ export const DataTableColumnHeader = <TData, TValue>({header,className,}: DataTableColumnHeaderProps<TData, TValue>) => {+ if (!header) {+ return null;+ }+if (!column.getCanSort() && !column.getCanFilter()) {return <div className={cn(className)}>{header}</div>;}@@ -104,7 +108,11 @@ export const DataTableColumnHeader = <TData, TValue>({<DropdownMenuContent align="start">{renderSorts()}<DropdownMenuItem- onClick={() => navigator.clipboard.writeText(column.id)}+ onClick={() =>+ navigator.clipboard.writeText(+ typeof header === "string" ? header : column.id,+ )+ }><CopyIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />Copy column namediff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex 7751208318..acbb626485 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -37,7 +37,7 @@ function getColumnInfo<T>(items: T[]): ColumnInfo[] {}// We will be a bit defensive and assume values are not homogeneous.// If any is a mimetype, then we will treat it as a mimetype (i.e. not sortable)- Object.entries(item as object).forEach(([key, value]) => {+ Object.entries(item as object).forEach(([key, value], idx) => {const currentValue = keys.get(key);if (!currentValue) {// Set for the first time@@ -71,16 +71,17 @@ export function generateColumns<T>({fieldTypes,}: {items: T[];- rowHeaders: Array<ColumnDef<T>>;+ rowHeaders: string[];selection: "single" | "multi" | null;showColumnSummaries: boolean;fieldTypes?: Record<string, DataType>;}): Array<ColumnDef<T>> {const columnInfo = getColumnInfo(items);+ const rowHeadersSet = new Set(rowHeaders);const columns = columnInfo.map(- (info): ColumnDef<T> => ({- id: info.key,+ (info, idx): ColumnDef<T> => ({+ id: info.key || `__m_column__${idx}`,// Use an accessorFn instead of an accessorKey because column names// may have periods in them ...// https://github.com/TanStack/table/issues/1671@@ -89,6 +90,11 @@ export function generateColumns<T>({return (row as any)[info.key];},header: ({ column }) => {+ // Row headers have no summaries+ if (rowHeadersSet.has(info.key)) {+ return <DataTableColumnHeader header={info.key} column={column} />;+ }+if (!showColumnSummaries) {return <DataTableColumnHeader header={info.key} column={column} />;}@@ -102,6 +108,11 @@ export function generateColumns<T>({);},cell: ({ renderValue, getValue }) => {+ // Row headers are bold+ if (rowHeadersSet.has(info.key)) {+ return <b>{String(renderValue())}</b>;+ }+const value = getValue();if (isPrimitiveOrNullish(value)) {const rendered = renderValue();@@ -112,20 +123,18 @@ export function generateColumns<T>({}return <MimeCell value={value} />;},- enableSorting: info.type === "primitive",+ // Only enable sorting for primitive types and non-row headers+ enableSorting: info.type === "primitive" && !rowHeadersSet.has(info.key),// Remove any default filteringfilterFn: undefined,meta: {type: info.type,+ rowHeader: rowHeadersSet.has(info.key),filterType: getFilterTypeForFieldType(fieldTypes?.[info.key]),},}),);- if (rowHeaders.length > 0) {- columns.unshift(...rowHeaders);- }-if (selection === "single" || selection === "multi") {columns.unshift({id: "select",@@ -158,29 +167,6 @@ 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 header={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/filters.ts b/frontend/src/components/data-table/filters.tsindex f240fbfc36..2d447637ce 100644--- a/frontend/src/components/data-table/filters.ts+++ b/frontend/src/components/data-table/filters.ts@@ -9,6 +9,7 @@ declare module "@tanstack/react-table" {//allows us to define custom properties for our columnsinterface ColumnMeta<TData extends RowData, TValue> {type?: "primitive" | "mime";+ rowHeader?: boolean;filterType?: FilterType;}}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex bed84b5c08..fc75d83b55 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -2,10 +2,7 @@import { memo, useEffect, useMemo, useState } from "react";import { z } from "zod";import { DataTable } from "../../components/data-table/data-table";-import {- generateColumns,- generateIndexColumns,-} from "../../components/data-table/columns";+import { generateColumns } from "../../components/data-table/columns";import { Labeled } from "./common/labeled";import { useAsyncData } from "@/hooks/useAsyncData";import { Alert, AlertTitle } from "@/components/ui/alert";@@ -58,7 +55,7 @@ interface Data<T> {showDownload: boolean;showFilters: boolean;showColumnSummaries: boolean;- rowHeaders: Array<[string, string[]]>;+ rowHeaders: string[];fieldTypes?: Record<string, DataType> | null;}@@ -94,7 +91,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")showDownload: z.boolean().default(false),showFilters: z.boolean().default(false),showColumnSummaries: z.boolean().default(true),- rowHeaders: z.array(z.tuple([z.string(), z.array(z.any())])),+ rowHeaders: z.array(z.string()),fieldTypes: z.record(z.enum(["boolean", "integer", "number", "date", "string", "unknown"]),@@ -336,7 +333,7 @@ const DataTableComponent = ({() =>generateColumns({items: data,- rowHeaders: generateIndexColumns(rowHeaders),+ rowHeaders: rowHeaders,selection,showColumnSummaries: showColumnSummaries,fieldTypes: fieldTypes ?? {},diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex 20453820af..bb89ff46e9 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -36,7 +36,7 @@ type PluginFunctions = {url: string;has_more: boolean;total_rows: number;- row_headers: Array<[string, string[]]>;+ row_headers: string[];supports_code_sample: boolean;}>;get_column_values: (req: { column: string }) => Promise<{@@ -70,7 +70,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")url: z.string(),has_more: z.boolean(),total_rows: z.number(),- row_headers: z.array(z.tuple([z.string(), z.array(z.any())])),+ row_headers: z.array(z.string()),supports_code_sample: z.boolean(),}),),diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex e5cea01dd6..47f6f2d75f 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -39,7 +39,9 @@ class GetDataFrameResponse:url: strhas_more: booltotal_rows: int- row_headers: List[tuple[str, List[str | int | float]]]+ # List of column names that are actually row headers+ # This really only applies to Pandas, that has special index columns+ row_headers: List[str]supports_code_sample: booldiff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex c470205c3c..7b85931802 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -131,7 +131,7 @@ class DefaultTableManager(TableManager[JsonTableData]):])- def get_row_headers(self) -> list[tuple[str, list[str | int | float]]]:+ def get_row_headers(self) -> list[str]:return []def _as_table_manager(self) -> TableManager[Any]:diff --git a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py b/marimo/_plugins/ui/_impl/tables/df_protocol_table.pyindex ff1a25779d..2b4e0a2be0 100644--- a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py+++ b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py@@ -82,7 +82,7 @@ class DataFrameProtocolTableManager(TableManager[DataFrameLike]):def get_row_headers(self,- ) -> list[tuple[str, list[str | int | float]]]:+ ) -> list[str]:return []def get_field_types(self) -> FieldTypes:diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 96fd60df72..de473f58d3 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -26,8 +26,9 @@ class PandasTableManagerFactory(TableManagerFactory):type = "pandas"def to_csv(self) -> bytes:+ has_headers = len(self.get_row_headers()) > 0return self.data.to_csv(- index=False,+ index=has_headers,).encode("utf-8")def to_json(self) -> bytes:@@ -48,7 +49,7 @@ class PandasTableManagerFactory(TableManagerFactory):def get_row_headers(self,- ) -> list[tuple[str, list[str | int | float]]]:+ ) -> list[str]:return PandasTableManager._get_row_headers_for_index(self.data.index)@@ -60,8 +61,9 @@ class PandasTableManagerFactory(TableManagerFactory):@staticmethoddef _get_row_headers_for_index(index: pd.Index[Any],- ) -> list[tuple[str, list[str | int | float]]]:- if isinstance(index, pd.RangeIndex):+ ) -> list[str]:+ # Ignore if it's the default index with no name+ if index.name is None and isinstance(index, pd.RangeIndex):return []if isinstance(index, pd.MultiIndex):@@ -75,48 +77,7 @@ class PandasTableManagerFactory(TableManagerFactory):)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]-- if isinstance(index, pd.DatetimeIndex):- # Format to Y-m-d if the time is 00:00:00- formatted: list[str] = index.strftime(- "%Y-%m-%d %H:%M:%S"- ).tolist()- if all(time.endswith(" 00:00:00") for time in formatted):- return [- (- index.name or "",- index.strftime("%Y-%m-%d").tolist(),- )- ]- return [- (- index.name or "",- index.strftime("%Y-%m-%d %H:%M:%S").tolist(),- )- ]-- if isinstance(index, pd.TimedeltaIndex):- return [- (- index.name or "",- index.astype(str).tolist(),- )- ]-- return []+ return [str(index.name or "")]def get_field_types(self) -> FieldTypes:return {diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 6424df2d75..ecefbbb803 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -46,7 +46,7 @@ class PolarsTableManagerFactory(TableManagerFactory):def get_row_headers(self,- ) -> list[tuple[str, list[str | int | float]]]:+ ) -> list[str]:return []@staticmethoddiff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.pyindex 03f3ea1731..8be1ca48f5 100644--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py@@ -75,7 +75,7 @@ class PyArrowTableManagerFactory(TableManagerFactory):def get_row_headers(self,- ) -> list[tuple[str, list[str | int | float]]]:+ ) -> list[str]:return []@staticmethoddiff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 3903e7bcef..a9744a97b0 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -68,7 +68,7 @@ class TableManager(abc.ABC, Generic[T]):raise NotImplementedError@abc.abstractmethod- def get_row_headers(self) -> list[tuple[str, list[str | int | float]]]:+ def get_row_headers(self) -> list[str]:raise NotImplementedErrordef get_field_types(self) -> FieldTypes:diff --git a/marimo/_smoke_tests/bugs/1689.py b/marimo/_smoke_tests/bugs/1689.pynew file mode 100644index 0000000000..0cfedc9636--- /dev/null+++ b/marimo/_smoke_tests/bugs/1689.py@@ -0,0 +1,68 @@+import marimo++__generated_with = "0.6.23"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ import pandas as pd++ data = {"col3": range(3), "col1": [0, 1, 2], "col2": [6, 5, 4]}++ df = pd.DataFrame(data)+ df_with_index = pd.DataFrame(data, index=[0, 1, 2])+ df_with_named_index = pd.DataFrame(data)+ df_with_named_index.index.names = ["idx"]+ return data, df, df_with_index, df_with_named_index, mo, pd+++def __(pd):+ _data = pd.DataFrame(+ {+ "Animal": ["Falcon", "Falcon", "Parrot", "Parrot"],+ "Max Speed": [380.0, 370.0, 24.0, 26.0],+ }+ )+ agg_df = _data.groupby(["Animal"]).mean()+ return agg_df,+++def __(df, df_with_index, df_with_named_index):+ [+ df.index,+ df_with_index.index,+ df_with_named_index.index,+ ]+ return+++def __(agg_df, mo):+ mo.ui.table(agg_df)+ return+++def __(df, mo):+ mo.ui.table(df)+ return+++def __(df_with_index, mo):+ mo.ui.table(df_with_index)+ return+++def __(df_with_named_index, mo):+ mo.ui.table(df_with_named_index)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex f7ea575827..75ec392c6b 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -89,10 +89,7 @@ class TestPandasTableManager(unittest.TestCase):index=pd.to_datetime(["2021-01-01", "2021-06-01", "2021-09-01"]),)manager = self.factory.create()(data)- expected_headers = [- ("", ["2021-01-01", "2021-06-01", "2021-09-01"]),- ]- assert manager.get_row_headers() == expected_headers+ assert manager.get_row_headers() == [""]def test_get_row_headers_timedelta_index(self) -> None:import pandas as pd@@ -106,10 +103,7 @@ class TestPandasTableManager(unittest.TestCase):index=pd.to_timedelta(["1 days", "2 days", "3 days"]),)manager = self.factory.create()(data)- expected_headers = [- ("", ["1 days", "2 days", "3 days"]),- ]- assert manager.get_row_headers() == expected_headers+ assert manager.get_row_headers() == [""]def test_get_row_headers_multi_index(self) -> None:import pandas as pd@@ -125,11 +119,7 @@ class TestPandasTableManager(unittest.TestCase):),)manager = self.factory.create()(data)- expected_headers = [- ("X", ["a", "b", "c"]),- ("Y", [1, 2, 3]),- ]- assert manager.get_row_headers() == expected_headers+ assert manager.get_row_headers() == ["X", "Y"]def test_is_type(self) -> None:assert self.manager.is_type(self.data)@@ -339,6 +329,20 @@ class TestPandasTableManager(unittest.TestCase):expected_df = self.data.sort_values("A", ascending=False)assert sorted_df.equals(expected_df)+ def test_sort_values_with_index(self) -> None:+ import pandas as pd++ data = pd.DataFrame(+ {+ "A": [1, 3, 2],+ },+ index=[1, 3, 2],+ )+ data.index.name = "index"+ manager = self.factory.create()(data)+ sorted_df = manager.sort_values("A", descending=True).data+ assert sorted_df.index.tolist() == [3, 2, 1]+def test_get_unique_column_values(self) -> None:column = "B"assert self.manager.get_unique_column_values(column) == ["a", "b", "c"]diff --git a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.pyindex 4b5fe56c8b..1c727e1a8d 100644--- a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py+++ b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, List+from typing import Anyimport pytest@@ -13,7 +13,7 @@ HAS_PANDAS = DependencyManager.has_pandas()def _get_row_headers(data: Any,-) -> list[tuple[str, list[str | int | float]]]:+) -> list[str]:manager = get_table_manager(data)return manager.get_row_headers()@@ -24,12 +24,10 @@ def _get_row_headers(def test_get_row_headers_pandas() -> None:import pandas as pd- expected: List[tuple[str, List[str]]]-# Test with pandas DataFramedf = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})df.index.name = "Index"- assert _get_row_headers(df) == []+ assert _get_row_headers(df) == ["Index"]# Test with MultiIndexarrays = [@@ -37,11 +35,7 @@ def test_get_row_headers_pandas() -> None:["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+ assert _get_row_headers(df_multi) == ["", ""]# Test with RangeIndexdf_range = pd.DataFrame({"A": range(3)})@@ -50,14 +44,12 @@ def test_get_row_headers_pandas() -> None:# Test with categorical Indexdf_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+ assert _get_row_headers(df_cat) == [""]# Test with named categorical Indexdf_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+ assert _get_row_headers(df_cat) == ["Colors"]def test_get_row_headers_list() -> None: