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: .schema perf improvements (#3108)
Myles Scolnickdecd87d61c8f
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex 31c37e1973..d38f891556 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -2,10 +2,11 @@from __future__ import annotationsimport json+from functools import cached_propertyfrom typing import Any, Optional, Tuple, Union, castimport narwhals.stable.v1 as nw-from narwhals.typing import IntoFrameT+from narwhals.stable.v1.typing import IntoFrameTfrom marimo._data.models import ColumnSummary, ExternalDataTypefrom marimo._plugins.ui._impl.tables.format import (@@ -101,10 +102,14 @@ class NarwhalsTableManager(def is_type(value: Any) -> bool:return can_narwhalify(value)+ @cached_property+ def nw_schema(self) -> nw.Schema:+ return cast(nw.Schema, self.data.schema)+def get_field_type(self, column_name: str) -> Tuple[FieldType, ExternalDataType]:- dtype = self.data.schema[column_name]+ dtype = self.nw_schema[column_name]dtype_string = str(dtype)if is_narwhals_string_type(dtype):return ("string", dtype_string)@@ -130,7 +135,7 @@ class NarwhalsTableManager(query = query.lower()expressions: list[Any] = []- for column, dtype in self.data.schema.items():+ for column, dtype in self.nw_schema.items():if dtype == nw.String:expressions.append(nw.col(column).str.contains(query))elif dtype == nw.List(nw.String):@@ -166,7 +171,7 @@ class NarwhalsTableManager(def _get_summary_internal(self, column: str) -> ColumnSummary:# If column is not in the dataframe, return an empty summary- if column not in self.data.schema:+ if column not in self.nw_schema:return ColumnSummary()col = self.data[column]total = len(col)@@ -224,9 +229,9 @@ class NarwhalsTableManager(return ColumnSummary(total=total,nulls=col.null_count(),- unique=col.n_unique()- if is_narwhals_integer_type(col.dtype)- else None,+ unique=(+ col.n_unique() if is_narwhals_integer_type(col.dtype) else None+ ),min=col.min(),max=col.max(),mean=col.mean(),@@ -255,10 +260,10 @@ class NarwhalsTableManager(return Nonedef get_num_columns(self) -> int:- return len(self.data.schema.names())+ return len(self.nw_schema.names())def get_column_names(self) -> list[str]:- return self.data.schema.names()+ return self.nw_schema.names()def get_unique_column_values(self, column: str) -> list[str | int | float]:return self.data[column].unique().to_list()diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 02850ea28a..239f37b0fb 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from functools import cached_propertyfrom typing import Any, Optional, Tupleimport narwhals.stable.v1 as nw@@ -31,13 +32,12 @@ class PandasTableManagerFactory(TableManagerFactory):type = "pandas"def __init__(self, data: pd.DataFrame) -> None:+ self._original_data = datasuper().__init__(nw.from_native(data))- def as_pandas_frame(self) -> pd.DataFrame:- native: Any = self.data.to_native()- if isinstance(native, pd.DataFrame):- return native- raise ValueError(f"Unsupported native type: {type(native)}")+ @cached_property+ def schema(self) -> pd.Series[Any]:+ return self._original_data.dtypes # type: ignore# We override narwhals's to_csv to handle pandas# headers@@ -47,16 +47,13 @@ class PandasTableManagerFactory(TableManagerFactory):has_headers = len(self.get_row_headers()) > 0return (self.apply_formatting(format_mapping)- .as_pandas_frame()- .to_csv(index=has_headers)+ ._original_data.to_csv(index=has_headers).encode("utf-8"))def to_json(self) -> bytes:- return (- self.as_pandas_frame()- .to_json(orient="records")- .encode("utf-8")+ return self._original_data.to_json(orient="records").encode(+ "utf-8")def apply_formatting(@@ -65,7 +62,7 @@ class PandasTableManagerFactory(TableManagerFactory):if not format_mapping:return self- _data = self.as_pandas_frame().copy()+ _data = self._original_data.copy()for col in _data.columns:if col in format_mapping:_data[col] = _data[col].apply(@@ -81,7 +78,7 @@ class PandasTableManagerFactory(TableManagerFactory):self,) -> list[str]:return PandasTableManager._get_row_headers_for_index(- self.as_pandas_frame().index+ self._original_data.index)@staticmethod@@ -114,14 +111,13 @@ class PandasTableManagerFactory(TableManagerFactory):def get_field_type(self, column_name: str) -> Tuple[FieldType, ExternalDataType]:- data = self.as_pandas_frame()- series = data[column_name]+ dtype = self.schema[column_name]# 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(series, pd.DataFrame):- dtype = str(series.columns.dtype)+ if isinstance(dtype, pd.DataFrame):+ dtype = str(dtype.columns.dtype)else:- dtype = str(series.dtype)+ dtype = str(dtype)if dtype.startswith("interval"):return ("string", dtype)@@ -151,6 +147,6 @@ class PandasTableManagerFactory(TableManagerFactory):def get_unique_column_values(self, column: str) -> list[str | int | float]:- return self.as_pandas_frame()[column].unique().tolist() # type: ignore[return-value,no-any-return]+ return self._original_data[column].unique().tolist() # type: ignore[return-value,no-any-return]return PandasTableManagerdiff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 43bc773511..a1494147e1 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from functools import cached_propertyfrom typing import Any, Optional, Tuple, Unionimport narwhals.stable.v1 as nw@@ -37,24 +38,20 @@ class PolarsTableManagerFactory(TableManagerFactory):def __init__(self, data: Union[pl.DataFrame, pl.LazyFrame]) -> None:+ self._original_data = datasuper().__init__(nw.from_native(data))def collect(self) -> pl.DataFrame:- native: Any = self.data.to_native()+ native: Any = self._original_dataif isinstance(native, pl.LazyFrame):return native.collect()if isinstance(native, pl.DataFrame):return nativeraise ValueError(f"Unsupported native type: {type(native)}")- def as_polars_frame(self) -> Union[pl.DataFrame, pl.LazyFrame]:- native: Any = self.data.to_native()- if isinstance(native, (pl.LazyFrame, pl.DataFrame)):- return native- raise ValueError(f"Unsupported native type: {type(native)}")-+ @cached_propertydef schema(self) -> dict[str, pl.DataType]:- return self.as_polars_frame().schema+ return self._original_data.schema# We override narwhals's to_csv to handle polars# nested data types.@@ -143,7 +140,7 @@ class PolarsTableManagerFactory(TableManagerFactory):query = query.lower()expressions: list[pl.Expr] = []- for column, dtype in self.schema().items():+ for column, dtype in self.schema.items():if dtype == pl.String:expressions.append(pl.col(column).str.contains(query))elif dtype == pl.List(pl.Utf8):@@ -166,7 +163,7 @@ class PolarsTableManagerFactory(TableManagerFactory):for expr in expressions[1:]:or_expr = or_expr | expr- filtered = self.as_polars_frame().filter(or_expr)+ filtered = self._original_data.filter(or_expr)return PolarsTableManager(filtered)# We override the default implementation to use polars's@@ -174,7 +171,7 @@ class PolarsTableManagerFactory(TableManagerFactory):def get_field_type(self, column_name: str) -> Tuple[FieldType, ExternalDataType]:- dtype = self.schema()[column_name]+ dtype = self.schema[column_name]try:dtype_string = dtype._string_repr()except (TypeError, AttributeError):diff --git a/marimo/_smoke_tests/issues/3107-dataframe-perf.py b/marimo/_smoke_tests/issues/3107-dataframe-perf.pynew file mode 100644index 0000000000..ceefe17b08--- /dev/null+++ b/marimo/_smoke_tests/issues/3107-dataframe-perf.py@@ -0,0 +1,85 @@+import marimo++__generated_with = "0.9.33"+app = marimo.App(width="medium")+++def __():+ import polars as pl+ import numpy as np+ from typing import Tuple+ import marimo as mo+++ def create_test_dataframe(num_rows: int) -> Tuple[pl.DataFrame, list[str]]:+ """+ Create a large test dataframe with various column types including 1200 float columns.++ Args:+ num_rows: Number of rows to generate++ Returns:+ Tuple of (DataFrame, list of group values)+ """+ # Set random seed for reproducibility+ np.random.seed(42)++ # Generate random data for different column types+ data = {+ "int_col1": np.random.randint(0, 1000000, num_rows),+ "int_col2": np.random.randint(-1000000, 1000000, num_rows),+ "float_col1": np.random.normal(0, 1, num_rows),+ "float_col2": np.random.uniform(0, 100, num_rows),+ "str_col1": np.random.choice(["A", "B", "C", "D", "E"], num_rows),+ "str_col2": [f"val_{i}" for i in np.random.randint(0, 1000, num_rows)],+ "bool_col1": np.random.choice([True, False], num_rows),+ "bool_col2": np.random.choice([True, False], num_rows),+ "group": np.random.choice(+ ["group1", "group2", "group3", "group4"], num_rows+ ),+ }++ # Add 1200 float columns with different distributions+ for i in range(1200):+ if i % 3 == 0:+ # Normal distribution+ data[f"float_normal_{i}"] = np.random.normal(0, 1, num_rows)+ elif i % 3 == 1:+ # Uniform distribution+ data[f"float_uniform_{i}"] = np.random.uniform(-100, 100, num_rows)+ else:+ # Exponential distribution+ data[f"float_exp_{i}"] = np.random.exponential(1, num_rows)++ # Create the original derived columns+ data.update(+ {+ f"derived_col_{i}": data["int_col1"]+ + np.random.randint(0, 100, num_rows)+ for i in range(10)+ }+ )++ df = pl.DataFrame(data)+ unique_groups = df["group"].unique().to_list()++ return df+ return Tuple, create_test_dataframe, mo, np, pl+++def __(create_test_dataframe):+ num_rows = 10+ df = create_test_dataframe(num_rows)+ return df, num_rows+++def __(df, pl):+ x = df.filter(pl.col("group") == "group2")+ return (x,)+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.pyindex a2157c89eb..9160a5a17c 100644--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py@@ -15,6 +15,7 @@ from marimo._plugins.ui._impl.tables.narwhals_table import (NarwhalsTableManager,)from marimo._plugins.ui._impl.tables.table_manager import TableManager+from marimo._plugins.ui._impl.tables.utils import get_table_managerfrom marimo._utils.narwhals_utils import unwrap_py_scalarfrom tests._data.mocks import create_dataframesfrom tests.mocks import snapshotter@@ -771,3 +772,25 @@ def test_get_sample_values_with_metadata_only_frame(df: Any) -> None:assert sample_values == []sample_values = manager.get_sample_values("B")assert sample_values == []++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ create_dataframes({f"col_{i}": [1, 2, 3] for i in range(2000)}),+)+def test_get_field_types_with_many_columns_is_performant(df: Any) -> None:+ import time++ manager = get_table_manager(df)++ start_time = time.time()+ manager.get_field_types()+ end_time = time.time()++ # This can be slow if get_field_types is not optimized.+ # https://github.com/marimo-team/marimo/issues/3107+ total_ms = (end_time - start_time) * 1000+ assert (+ total_ms < 300+ ), f"Total time: {total_ms}ms for {df.shape[1]} columns with {type(df)}"