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: fix regression of rendering pandas tables with custom index (#2813)

Myles Scolnick4f59c97708fc
diff --git a/frontend/src/components/data-table/__test__/columns.test.tsx b/frontend/src/components/data-table/__test__/columns.test.tsx
index c890adc391..f605b48a53 100644
--- a/frontend/src/components/data-table/__test__/columns.test.tsx
+++ b/frontend/src/components/data-table/__test__/columns.test.tsx
@@ -1,9 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { expect, test } from "vitest";
+import { describe, expect, it, test } from "vitest";
import { uniformSample } from "../uniformSample";
import { UrlDetector } from "../url-detector";
import { render } from "@testing-library/react";
-import { inferFieldTypes } from "../columns";
+import { generateColumns, inferFieldTypes } from "../columns";
+import type { FieldTypesWithExternalType } from "../types";
test("uniformSample", () => {
const items = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
@@ -118,3 +119,78 @@ test("inferFieldTypes with mimetypes", () => {
}
`);
});
+
+describe("generateColumns", () => {
+ const fieldTypes: FieldTypesWithExternalType = {
+ name: ["string", "text"],
+ age: ["number", "integer"],
+ };
+
+ it("should generate columns with row headers", () => {
+ const columns = generateColumns({
+ rowHeaders: ["name"],
+ selection: null,
+ fieldTypes,
+ });
+
+ expect(columns).toHaveLength(3);
+ expect(columns[0].id).toBe("name");
+ expect(columns[0].meta?.rowHeader).toBe(true);
+ expect(columns[0].enableSorting).toBe(true);
+ });
+
+ it("should generate columns with nameless row headers", () => {
+ const columns = generateColumns({
+ rowHeaders: [""],
+ selection: null,
+ fieldTypes,
+ });
+
+ expect(columns).toHaveLength(3);
+ expect(columns[0].id).toMatchInlineSnapshot(`"__m_column__0"`);
+ expect(columns[0].meta?.rowHeader).toBe(true);
+ expect(columns[0].enableSorting).toBe(false);
+ });
+
+ it("should include selection column for multi selection", () => {
+ const columns = generateColumns({
+ rowHeaders: [],
+ selection: "multi",
+ fieldTypes,
+ });
+
+ expect(columns[0].id).toBe("__select__");
+ expect(columns[0].enableSorting).toBe(false);
+ });
+
+ it("should generate columns with correct meta data", () => {
+ const columns = generateColumns({
+ rowHeaders: [],
+ selection: null,
+ fieldTypes,
+ });
+
+ expect(columns.length).toBe(2);
+ expect(columns[0].meta?.dataType).toBe("string");
+ expect(columns[1].meta?.dataType).toBe("number");
+ });
+
+ it("should handle text justification and wrapping", () => {
+ const columns = generateColumns({
+ rowHeaders: [],
+ selection: null,
+ fieldTypes,
+ textJustifyColumns: { name: "center" },
+ wrappedColumns: ["age"],
+ });
+
+ // Assuming getCellStyleClass is a function that returns a class name
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const cell = (columns[0].cell as any)({
+ column: columns[0],
+ renderValue: () => "John",
+ getValue: () => "John",
+ });
+ expect(cell?.props.className).toContain("center");
+ });
+});
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 2f82d68965..abcd3b59cc 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -14,7 +14,6 @@ import type { FilterType } from "./filters";
import type { FieldTypesWithExternalType } from "./types";
import { UrlDetector } from "./url-detector";
import { cn } from "@/utils/cn";
-import { Objects } from "@/utils/objects";
import { uniformSample } from "./uniformSample";
function inferDataType(value: unknown): DataType {
@@ -94,8 +93,27 @@ export function generateColumns<T>({
}): Array<ColumnDef<T>> {
const rowHeadersSet = new Set(rowHeaders);
- const columns = Objects.entries(fieldTypes).map(
- ([key, types], idx): ColumnDef<T> => ({
+ const getMeta = (key: string) => {
+ const types = fieldTypes[key];
+ const isRowHeader = rowHeadersSet.has(key);
+
+ if (isRowHeader || !types) {
+ return {
+ rowHeader: isRowHeader,
+ };
+ }
+
+ return {
+ rowHeader: isRowHeader,
+ filterType: getFilterTypeForFieldType(types[0]),
+ dtype: types[1],
+ dataType: types[0],
+ };
+ };
+
+ const columnKeys = [...rowHeaders, ...Object.keys(fieldTypes)];
+ const columns = columnKeys.map(
+ (key, idx): ColumnDef<T> => ({
id: key || `${NAMELESS_COLUMN_PREFIX}${idx}`,
// Use an accessorFn instead of an accessorKey because column names
// may have periods in them ...
@@ -174,12 +192,10 @@ export function generateColumns<T>({
},
// Remove any default filtering
filterFn: undefined,
- meta: {
- rowHeader: rowHeadersSet.has(key),
- filterType: getFilterTypeForFieldType(types[0]),
- dtype: types[1],
- dataType: types[0],
- },
+ // Can only sort if key is defined
+ // For example, unnamed index columns, won't be sortable
+ enableSorting: !!key,
+ meta: getMeta(key),
}),
);
diff --git a/marimo/_smoke_tests/df_index.py b/marimo/_smoke_tests/df_index.py
new file mode 100644
index 0000000000..7e9b52b1f6
--- /dev/null
+++ b/marimo/_smoke_tests/df_index.py
@@ -0,0 +1,68 @@
+import marimo
+
+__generated_with = "0.9.15"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ import pandas as pd
+ import numpy as np
+ return mo, np, pd
+
+
+def __(np):
+ data = np.random.randn(100, 2)
+ columns = ["A", "B"]
+ return columns, data
+
+
+def __(columns, data, pd):
+ df_no_index = pd.DataFrame(data, columns=columns)
+ df_no_index
+ return (df_no_index,)
+
+
+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
+ return (df_date_index,)
+
+
+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,)
+
+
+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,)
+
+
+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
+
+
+if __name__ == "__main__":
+ app.run()