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: show dtypes for idexes in tables (#5694)

Shahmir Varqha2338b325a11a
diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsx
index 9d18dbe7fe..eab423501a 100644
--- a/frontend/src/components/data-table/__tests__/columns.test.tsx
+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx
@@ -166,7 +166,7 @@ describe("generateColumns", () => {
it("should generate columns with row headers", () => {
const columns = generateColumns({
- rowHeaders: ["name"],
+ rowHeaders: [["name", ["string", "text"]]],
selection: null,
fieldTypes,
});
@@ -179,7 +179,7 @@ describe("generateColumns", () => {
it("should generate columns with nameless row headers", () => {
const columns = generateColumns({
- rowHeaders: [""],
+ rowHeaders: [["", ["string", "text"]]],
selection: null,
fieldTypes,
});
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 153cc38c89..2901b4fd16 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -104,7 +104,7 @@ export function generateColumns<T>({
showDataTypes,
calculateTopKRows,
}: {
- rowHeaders: string[];
+ rowHeaders: FieldTypesWithExternalType;
selection: DataTableSelection;
fieldTypes: FieldTypesWithExternalType;
chartSpecModel?: ColumnChartSpecModel<unknown>;
@@ -113,7 +113,8 @@ export function generateColumns<T>({
showDataTypes?: boolean;
calculateTopKRows?: CalculateTopKRows;
}): Array<ColumnDef<T>> {
- const rowHeadersSet = new Set(rowHeaders);
+ // Row-headers are typically index columns
+ const rowHeadersSet = new Set(rowHeaders.map(([columnName]) => columnName));
const typesByColumn = Maps.keyBy(fieldTypes, (entry) => entry[0]);
@@ -122,8 +123,11 @@ export function generateColumns<T>({
const isRowHeader = rowHeadersSet.has(key);
if (isRowHeader || !types) {
+ const types = rowHeaders.find(([columnName]) => columnName === key)?.[1];
return {
rowHeader: isRowHeader,
+ dtype: types?.[1],
+ dataType: types?.[0],
};
}
@@ -135,8 +139,8 @@ export function generateColumns<T>({
};
};
- const columnKeys = [
- ...rowHeaders,
+ const columnKeys: string[] = [
+ ...rowHeadersSet,
...fieldTypes.map(([columnName]) => columnName),
];
@@ -173,7 +177,7 @@ export function generateColumns<T>({
const headerWithType = (
<div className="flex flex-col">
- <span className="font-bold">{key}</span>
+ <span className="font-bold">{key === "" ? " " : key}</span>
{dtypeHeader}
</div>
);
@@ -200,11 +204,6 @@ export function generateColumns<T>({
},
cell: ({ column, renderValue, getValue, cell }) => {
- // Row headers are bold
- if (rowHeadersSet.has(key)) {
- return <b>{String(renderValue())}</b>;
- }
-
function selectCell() {
if (selection !== "single-cell" && selection !== "multi-cell") {
return;
@@ -227,13 +226,20 @@ export function generateColumns<T>({
isCellSelected,
);
- return renderCellValue(
+ const renderedCell = renderCellValue(
column,
renderValue,
getValue,
selectCell,
cellStyles,
);
+
+ // Row headers are bold
+ if (rowHeadersSet.has(key)) {
+ return <b>{renderedCell}</b>;
+ }
+
+ return renderedCell;
},
// Remove any default filtering
filterFn: undefined,
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 4008f2b9ff..8d5ef8e1df 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -53,7 +53,6 @@ import { Button } from "@/components/ui/button";
import { DelayMount } from "@/components/utils/delay-mount";
import { type CellId, findCellId } from "@/core/cells/ids";
import { getFeatureFlag } from "@/core/config/feature-flag";
-import { DATA_TYPES } from "@/core/kernel/messages";
import { slotsController } from "@/core/slots/slots";
import { store } from "@/core/state/jotai";
import { isStaticNotebook } from "@/core/static/static-state";
@@ -72,7 +71,11 @@ import { createPlugin } from "../core/builder";
import { rpc } from "../core/rpc";
import { Banner } from "./common/error-banner";
import { Labeled } from "./common/labeled";
-import { ConditionSchema, type ConditionType } from "./data-frames/schema";
+import {
+ ConditionSchema,
+ type ConditionType,
+ columnToFieldTypesSchema,
+} from "./data-frames/schema";
type CsvURL = string;
export type TableData<T> = T[] | CsvURL;
@@ -163,7 +166,7 @@ interface Data<T> {
showPageSizeSelector: boolean;
showColumnExplorer: boolean;
showChartBuilder: boolean;
- rowHeaders: string[];
+ rowHeaders: FieldTypesWithExternalType;
fieldTypes?: FieldTypesWithExternalType | null;
freezeColumnsLeft?: string[];
freezeColumnsRight?: string[];
@@ -228,21 +231,14 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
showPageSizeSelector: z.boolean().default(true),
showColumnExplorer: z.boolean().default(true),
showChartBuilder: z.boolean().default(true),
- rowHeaders: z.array(z.string()),
+ rowHeaders: columnToFieldTypesSchema,
freezeColumnsLeft: z.array(z.string()).optional(),
freezeColumnsRight: z.array(z.string()).optional(),
textJustifyColumns: z
.record(z.enum(["left", "center", "right"]))
.optional(),
wrappedColumns: z.array(z.string()).optional(),
- fieldTypes: z
- .array(
- z.tuple([
- z.coerce.string(),
- z.tuple([z.enum(DATA_TYPES), z.string()]),
- ]),
- )
- .nullish(),
+ fieldTypes: columnToFieldTypesSchema.nullish(),
totalColumns: z.number(),
maxColumns: z.union([z.number(), z.literal("all")]).default("all"),
hasStableRowId: z.boolean().default(false),
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 3fc69bdc29..cef25c5d5a 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -8,7 +8,6 @@ import type { FieldTypesWithExternalType } from "@/components/data-table/types";
import { ReadonlyCode } from "@/components/editor/code/readonly-python-code";
import { Spinner } from "@/components/icons/spinner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { DATA_TYPES } from "@/core/kernel/messages";
import { useAsyncData } from "@/hooks/useAsyncData";
import { createPlugin } from "@/plugins/core/builder";
import { rpc } from "@/plugins/core/rpc";
@@ -21,6 +20,7 @@ import { TransformPanel } from "./panel";
import {
ConditionSchema,
type ConditionType,
+ columnToFieldTypesSchema,
type Transformations,
} from "./schema";
import type { ColumnDataTypes, ColumnId } from "./types";
@@ -45,7 +45,7 @@ type PluginFunctions = {
get_dataframe: (req: {}) => Promise<{
url: string;
total_rows: number;
- row_headers: string[];
+ row_headers: FieldTypesWithExternalType;
field_types: FieldTypesWithExternalType | null;
python_code?: string | null;
sql_code?: string | null;
@@ -94,10 +94,8 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")
z.object({
url: z.string(),
total_rows: z.number(),
- row_headers: z.array(z.string()),
- field_types: z.array(
- z.tuple([z.string(), z.tuple([z.enum(DATA_TYPES), z.string()])]),
- ),
+ row_headers: columnToFieldTypesSchema,
+ field_types: columnToFieldTypesSchema,
python_code: z.string().nullish(),
sql_code: z.string().nullish(),
}),
diff --git a/frontend/src/plugins/impl/data-frames/schema.ts b/frontend/src/plugins/impl/data-frames/schema.ts
index c07e6c07fc..6e0fc89fdf 100644
--- a/frontend/src/plugins/impl/data-frames/schema.ts
+++ b/frontend/src/plugins/impl/data-frames/schema.ts
@@ -2,6 +2,7 @@
import { z } from "zod";
import { FieldOptions, randomNumber } from "@/components/forms/options";
+import { DATA_TYPES } from "@/core/kernel/messages";
import {
AGGREGATION_FNS,
type ColumnId,
@@ -13,6 +14,10 @@ import {
type OperatorType,
} from "./utils/operators";
+export const columnToFieldTypesSchema = z.array(
+ z.tuple([z.coerce.string(), z.tuple([z.enum(DATA_TYPES), z.string()])]),
+);
+
export const column_id = z
.string()
.min(1, "Required")
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index a79771c487..a600f5d68c 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -49,9 +49,9 @@ from marimo._utils.parse_dataclass import parse_raw
class GetDataFrameResponse:
url: str
total_rows: Union[int, Literal["too_many"]]
- # List of column names that are actually row headers
+ # Columns that are actually row headers
# This really only applies to Pandas, that has special index columns
- row_headers: list[str]
+ row_headers: FieldTypes
field_types: FieldTypes
python_code: Optional[str] = None
sql_code: Optional[str] = None
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index a428a2342b..5d2561aaca 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -256,7 +256,7 @@ class DefaultTableManager(TableManager[JsonTableData]):
]
)
- def get_row_headers(self) -> list[str]:
+ def get_row_headers(self) -> FieldTypes:
return []
@functools.lru_cache(maxsize=5) # noqa: B019
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index cf5a759fc8..67efa0b556 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -18,6 +18,7 @@ from marimo._plugins.ui._impl.tables.polars_table import (
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
+ FieldTypes,
TableCell,
TableCoordinate,
TableManager,
@@ -89,9 +90,7 @@ class IbisTableManagerFactory(TableManagerFactory):
) -> TableManager[ibis.Table]:
return IbisTableManager(self.data.drop(columns))
- def get_row_headers(
- self,
- ) -> list[str]:
+ def get_row_headers(self) -> FieldTypes:
return []
@staticmethod
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index b76e8c0e90..4425689eb8 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -22,6 +22,7 @@ from marimo._plugins.ui._impl.tables.selection import INDEX_COLUMN_NAME
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
+ FieldTypes,
TableCell,
TableCoordinate,
TableManager,
@@ -155,9 +156,7 @@ class NarwhalsTableManager(
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]:
+ def get_row_headers(self) -> FieldTypes:
return []
@functools.lru_cache(maxsize=5) # noqa: B019
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 663b3d1d76..fc74fe0844 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -20,6 +20,7 @@ from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManager
from marimo._plugins.ui._impl.tables.selection import INDEX_COLUMN_NAME
from marimo._plugins.ui._impl.tables.table_manager import (
FieldType,
+ FieldTypes,
TableManager,
TableManagerFactory,
)
@@ -29,6 +30,9 @@ if TYPE_CHECKING:
LOGGER = _loggers.marimo_logger()
+if TYPE_CHECKING:
+ from pandas._typing import DtypeObj
+
def _maybe_convert_geopandas_to_pandas(data: pd.DataFrame) -> pd.DataFrame:
# Convert to pandas dataframe since geopandas will fail on
@@ -218,10 +222,8 @@ class PandasTableManagerFactory(TableManagerFactory):
# We override the default implementation to use pandas
# headers
- def get_row_headers(
- self,
- ) -> list[str]:
- return PandasTableManager._get_row_headers_for_index(
+ def get_row_headers(self) -> FieldTypes:
+ return self._get_row_headers_for_index(
self._original_data.index
)
@@ -229,26 +231,27 @@ class PandasTableManagerFactory(TableManagerFactory):
def is_type(value: Any) -> bool:
return isinstance(value, pd.DataFrame)
- @staticmethod
def _get_row_headers_for_index(
- index: pd.Index[Any],
- ) -> list[str]:
+ self, index: pd.Index[Any]
+ ) -> FieldTypes:
# 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):
# recurse
- headers: list[Any] = []
+ headers: FieldTypes = []
for i in range(index.nlevels):
headers.extend(
- PandasTableManager._get_row_headers_for_index(
+ self._get_row_headers_for_index(
index.get_level_values(i)
)
)
return headers
- return [str(index.name or "")]
+ dtype = index.dtype
+ field_type = self._map_dtype_to_field_type(dtype)
+ return [(str(index.name or ""), field_type)]
# We override the default implementation to use pandas's
# internal fields since they get displayed in the UI.
@@ -256,6 +259,11 @@ class PandasTableManagerFactory(TableManagerFactory):
self, column_name: str
) -> tuple[FieldType, ExternalDataType]:
dtype = self.schema[column_name]
+ return self._map_dtype_to_field_type(dtype)
+
+ def _map_dtype_to_field_type(
+ self, dtype: str | pd.DataFrame | DtypeObj
+ ) -> tuple[FieldType, ExternalDataType]:
# If a df has duplicate columns, it won't be a series, but
# a dataframe. In this case, we take the dtype of the columns
if isinstance(dtype, pd.DataFrame):
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 7b4650cfad..1ca77fc5f5 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -130,7 +130,7 @@ class TableManager(abc.ABC, Generic[T]):
pass
@abc.abstractmethod
- def get_row_headers(self) -> list[str]:
+ def get_row_headers(self) -> FieldTypes:
pass
@abc.abstractmethod
diff --git a/marimo/_smoke_tests/df_index.py b/marimo/_smoke_tests/df_index.py
index 7e9b52b1f6..715ba91c0c 100644
--- a/marimo/_smoke_tests/df_index.py
+++ b/marimo/_smoke_tests/df_index.py
@@ -1,11 +1,11 @@
import marimo
-__generated_with = "0.9.15"
+__generated_with = "0.14.12"
app = marimo.App(width="medium")
@app.cell
-def __():
+def _():
import marimo as mo
import pandas as pd
import numpy as np
@@ -13,21 +13,21 @@ def __():
@app.cell
-def __(np):
+def _(np):
data = np.random.randn(100, 2)
columns = ["A", "B"]
return columns, data
@app.cell
-def __(columns, data, pd):
+def _(columns, data, pd):
df_no_index = pd.DataFrame(data, columns=columns)
df_no_index
- return (df_no_index,)
+ return
@app.cell
-def __(columns, data, pd):
+def _(columns, data, pd):
_dates = pd.date_range(start="2023-01-01", periods=100, freq="D")
df_date_index = pd.DataFrame(data, index=_dates, columns=columns)
df_date_index
@@ -35,33 +35,39 @@ def __(columns, data, pd):
@app.cell
-def __(columns, data, pd):
+def _(columns, data, pd):
_dates = pd.date_range(start="2023-01-01", periods=100, freq="D")
df_date_index_with_name = pd.DataFrame(
data, index=pd.DatetimeIndex(_dates, name="date"), columns=columns
)
df_date_index_with_name
- return (df_date_index_with_name,)
+ return
@app.cell
-def __(columns, data, pd):
+def _(columns, data, pd):
_dates = pd.date_range(start="2023-01-01", periods=100, freq="D")
df_category_index = pd.DataFrame(
data, index=pd.CategoricalIndex(_dates), columns=columns
)
df_category_index
- return (df_category_index,)
+ return
@app.cell
-def __(columns, data, pd):
+def _(columns, data, pd):
index = pd.MultiIndex.from_tuples(
[(i, j) for i in range(5) for j in range(2)], names=["Level1", "Level2"]
)
df_multi_index = pd.DataFrame(data[:10], index=index, columns=columns)
df_multi_index
- return df_multi_index, index
+ return
+
+
+def _(df_date_index, mo):
+ mo.ui.dataframe(df_date_index)
+ return
if __name__ == "__main__":
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 7c2b28a135..b66fdc2f4a 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -375,7 +375,9 @@ class TestPandasTableManager(unittest.TestCase):
index=pd.to_datetime(["2021-01-01", "2021-06-01", "2021-09-01"]),
)
manager = self.factory.create()(data)
- assert manager.get_row_headers() == [""]
+ assert manager.get_row_headers() == [
+ ("", ("datetime", "datetime64[ns]"))
+ ]
def test_get_row_headers_timedelta_index(self) -> None:
data = pd.DataFrame(
@@ -387,7 +389,9 @@ class TestPandasTableManager(unittest.TestCase):
index=pd.to_timedelta(["1 days", "2 days", "3 days"]),
)
manager = self.factory.create()(data)
- assert manager.get_row_headers() == [""]
+ assert manager.get_row_headers() == [
+ ("", ("string", "timedelta64[ns]"))
+ ]
def test_get_row_headers_multi_index(self) -> None:
data = pd.DataFrame(
@@ -401,7 +405,10 @@ class TestPandasTableManager(unittest.TestCase):
),
)
manager = self.factory.create()(data)
- assert manager.get_row_headers() == ["X", "Y"]
+ assert manager.get_row_headers() == [
+ ("X", ("string", "object")),
+ ("Y", ("integer", "int64")),
+ ]
def test_is_type(self) -> None:
assert self.manager.is_type(self.data)
@@ -1060,7 +1067,10 @@ class TestPandasTableManager(unittest.TestCase):
index=[["a", "a", "b", "b"], [1, 2, 1, 2]],
)
manager = self.factory.create()(df)
- assert manager.get_row_headers() == ["", ""]
+ assert manager.get_row_headers() == [
+ ("", ("string", "object")),
+ ("", ("integer", "int64")),
+ ]
assert manager.get_num_rows() == 4
def test_get_field_types_with_datetime(self):
diff --git a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py
index a0d1104bfe..910b1c495d 100644
--- a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py
+++ b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py
@@ -6,6 +6,7 @@ from typing import Any
import pytest
from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.ui._impl.tables.table_manager import FieldTypes
from marimo._plugins.ui._impl.tables.utils import get_table_manager
HAS_PANDAS = DependencyManager.pandas.has()
@@ -16,7 +17,7 @@ HAS_PYARROW = DependencyManager.pyarrow.has()
def _get_row_headers(
data: Any,
-) -> list[str]:
+) -> FieldTypes:
manager = get_table_manager(data)
return manager.get_row_headers()
@@ -30,7 +31,7 @@ def test_get_row_headers_pandas() -> None:
# Test with pandas DataFrame
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df.index.name = "Index"
- assert _get_row_headers(df) == ["Index"]
+ assert _get_row_headers(df) == [("Index", ("integer", "int64"))]
# Test with MultiIndex
arrays = [
@@ -38,7 +39,10 @@ def test_get_row_headers_pandas() -> None:
["one", "two", "three"],
]
df_multi = pd.DataFrame({"A": range(3)}, index=arrays)
- assert _get_row_headers(df_multi) == ["", ""]
+ assert _get_row_headers(df_multi) == [
+ ("", ("string", "object")),
+ ("", ("string", "object")),
+ ]
# Test with RangeIndex
df_range = pd.DataFrame({"A": range(3)})
@@ -47,12 +51,12 @@ def test_get_row_headers_pandas() -> None:
# Test with categorical Index
df_cat = pd.DataFrame({"A": range(3)})
df_cat.index = pd.CategoricalIndex(["a", "b", "c"])
- assert _get_row_headers(df_cat) == [""]
+ assert _get_row_headers(df_cat) == [("", ("string", "category"))]
# Test with named categorical Index
df_cat = pd.DataFrame({"A": range(3)})
df_cat.index = pd.CategoricalIndex(["a", "b", "c"], name="Colors")
- assert _get_row_headers(df_cat) == ["Colors"]
+ assert _get_row_headers(df_cat) == [("Colors", ("string", "category"))]
def test_get_row_headers_list() -> None: