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.

improvement: use narwhals for more logic, get rid of dataprotocol and pyarrow logic (#2643)

Myles Scolnickb0cd2d03c2b8
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index e12edad891..735b008184 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -174,6 +174,9 @@ def _get_altair_chart(
request.column_name
]
+ if summary.total == 0:
+ return None, None, False
+
# For categorical columns with more than 10 unique values,
# we limit the chart to 10 items
should_limit_to_10_items = False
diff --git a/marimo/_data/series.py b/marimo/_data/series.py
index f9fc84b55f..2cc2e942dc 100644
--- a/marimo/_data/series.py
+++ b/marimo/_data/series.py
@@ -60,6 +60,8 @@ def get_number_series_info(series: nw.Series) -> NumberSeriesInfo:
assert_narwhals_series(series)
def validate_number(value: Any) -> float:
+ if hasattr(value, "as_py"):
+ return validate_number(value.as_py())
value = float(value)
if not isinstance(value, (int, float)):
raise ValueError("Expected a number. Got: " + str(type(value)))
@@ -97,6 +99,8 @@ def get_date_series_info(series: nw.Series) -> DateSeriesInfo:
return value.strftime("%Y-%m-%d")
if hasattr(value, "strftime"):
return cast(str, value.strftime("%Y-%m-%d"))
+ if hasattr(value, "as_py"):
+ return validate_date(value.as_py())
raise ValueError("Expected a date. Got: " + str(type(value)))
return DateSeriesInfo(
@@ -122,6 +126,8 @@ def get_datetime_series_info(series: nw.Series) -> DateSeriesInfo:
return value.strftime("%Y-%m-%d")
if hasattr(value, "strftime"):
return cast(str, value.strftime("%Y-%m-%d"))
+ if hasattr(value, "as_py"):
+ return validate_datetime(value.as_py())
raise ValueError("Expected a datetime. Got: " + str(type(value)))
return DateSeriesInfo(
diff --git a/marimo/_plugins/ui/_impl/tables/dataframe_protocol.py b/marimo/_plugins/ui/_impl/tables/dataframe_protocol.py
deleted file mode 100644
index 2d2bfbb38a..0000000000
--- a/marimo/_plugins/ui/_impl/tables/dataframe_protocol.py
+++ /dev/null
@@ -1,342 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-
-# Copied from https://github.com/data-apis/dataframe-api/blob/main/protocol/dataframe_protocol.py
-# since this is not published on PyPI.
-
-from __future__ import annotations
-
-import enum
-from abc import (
- ABC,
- abstractmethod,
-)
-from typing import (
- Any,
- Dict,
- Iterable,
- Optional,
- Sequence,
- Tuple,
- TypedDict,
-)
-
-
-class DlpackDeviceType(enum.IntEnum):
- """Integer enum for device type codes matching DLPack."""
-
- CPU = 1
- CUDA = 2
- CPU_PINNED = 3
- OPENCL = 4
- VULKAN = 7
- METAL = 8
- VPI = 9
- ROCM = 10
-
-
-class DtypeKind(enum.IntEnum):
- """
- Integer enum for data types.
-
- Attributes
- ----------
- INT : int
- Matches to signed integer data type.
- UINT : int
- Matches to unsigned integer data type.
- FLOAT : int
- Matches to floating point data type.
- BOOL : int
- Matches to boolean data type.
- STRING : int
- Matches to string data type (UTF-8 encoded).
- DATETIME : int
- Matches to datetime data type.
- CATEGORICAL : int
- Matches to categorical data type.
- """
-
- INT = 0
- UINT = 1
- FLOAT = 2
- BOOL = 20
- STRING = 21 # UTF-8
- DATETIME = 22
- CATEGORICAL = 23
-
-
-Dtype = Tuple[DtypeKind, int, str, str] # see Column.dtype
-
-
-class CategoricalDescription(TypedDict):
- # whether the ordering of dictionary indices is semantically meaningful
- is_ordered: bool
- # whether a dictionary-style mapping of categorical values to other objects exists # noqa: E501
- is_dictionary: bool
- # Python-level only (e.g. ``{int: str}``).
- # None if not a dictionary-style categorical.
- categories: Optional[Column]
-
-
-class Column(ABC):
- """
- A column object, with only the methods and properties required by the
- interchange protocol defined.
-
- A column can contain one or more chunks. Each chunk can contain up to three
- buffers - a data buffer, a mask buffer (depending on null representation),
- and an offsets buffer (if variable-size binary; e.g., variable-length
- strings).
-
- TBD: there's also the "chunk" concept here, which is implicit in Arrow as
- multiple buffers per array (= column here). Semantically it may make
- sense to have both: chunks were meant for example for lazy evaluation
- of data which doesn't fit in memory, while multiple buffers per column
- could also come from doing a selection operation on a single
- contiguous buffer.
-
- Given these concepts, one would expect chunks to be all of the same
- size (say a 10,000 row dataframe could have 10 chunks of 1,000 rows),
- while multiple buffers could have data-dependent lengths. Not an issue
- in pandas if one column is backed by a single NumPy array, but in
- Arrow it seems possible.
- Are multiple chunks *and* multiple buffers per column necessary for
- the purposes of this interchange protocol, or must producers either
- reuse the chunk concept for this or copy the data?
-
- Note: this Column object can only be produced by ``__dataframe__``, so
- doesn't need its own version or ``__column__`` protocol.
- """
-
- @abstractmethod
- def size(self) -> int:
- """
- Size of the column, in elements.
-
- Corresponds to DataFrame.num_rows() if column is a single chunk;
- equal to size of this current chunk otherwise.
-
- Is a method rather than a property because it may cause a (potentially
- expensive) computation for some dataframe implementations.
- """
- pass
-
- @property
- @abstractmethod
- def offset(self) -> int:
- """
- Offset of first element.
-
- May be > 0 if using chunks; for example for a column with N chunks of
- equal size M (only the last chunk may be shorter),
- ``offset = n * M``, ``n = 0 .. N-1``.
- """
- pass
-
- @property
- @abstractmethod
- def dtype(self) -> Dtype:
- """
- Dtype description as a tuple ``(kind, bit-width, format string, endianness)``.
-
- Bit-width : the number of bits as an integer
- Format string : data type description format string in Apache Arrow C
- Data Interface format.
- Endianness : current only native endianness (``=``) is supported
-
- Notes:
- - Kind specifiers are aligned with DLPack where possible (hence the
- jump to 20, leave enough room for future extension)
- - Masks must be specified as boolean with either bit width 1 (for bit
- masks) or 8 (for byte masks).
- - Dtype width in bits was preferred over bytes
- - Endianness isn't too useful, but included now in case in the future
- we need to support non-native endianness
- - Went with Apache Arrow format strings over NumPy format strings
- because they're more complete from a dataframe perspective
- - Format strings are mostly useful for datetime specification, and
- for categoricals.
- - For categoricals, the format string describes the type of the
- categorical in the data buffer. In case of a separate encoding of
- the categorical (e.g. an integer to string mapping), this can
- be derived from ``self.describe_categorical``.
- - Data types not included: complex, Arrow-style null, binary, decimal,
- and nested (list, struct, map, union) dtypes.
- """ # noqa: E501
- pass
-
- @property
- @abstractmethod
- def describe_categorical(self) -> CategoricalDescription:
- """
- If the dtype is categorical, there are two options:
- - There are only values in the data buffer.
- - There is a separate non-categorical Column encoding categorical values.
-
- Raises TypeError if the dtype is not categorical
-
- Returns the dictionary with description on how to interpret the data buffer:
- - "is_ordered" : bool, whether the ordering of dictionary indices is
- semantically meaningful.
- - "is_dictionary" : bool, whether a mapping of
- categorical values to other objects exists
- - "categories" : Column representing the (implicit) mapping of indices to
- category values (e.g. an array of cat1, cat2, ...).
- None if not a dictionary-style categorical.
-
- TBD: are there any other in-memory representations that are needed?
- """ # noqa: E501
- pass
-
- @property
- @abstractmethod
- def null_count(self) -> Optional[int]:
- """
- Number of null elements, if known.
-
- Note: Arrow uses -1 to indicate "unknown", but None seems cleaner.
- """
- pass
-
- @property
- @abstractmethod
- def metadata(self) -> Dict[str, Any]:
- """
- The metadata for the column. See `DataFrame.metadata` for more details.
- """
- pass
-
-
-class DataFrame(ABC):
- """
- A data frame class, with only the methods required by the interchange
- protocol defined.
-
- A "data frame" represents an ordered collection of named columns.
- A column's "name" must be a unique string.
- Columns may be accessed by name or by position.
-
- This could be a public data frame class, or an object with the methods and
- attributes defined on this DataFrame class could be returned from the
- ``__dataframe__`` method of a public data frame class in a library adhering
- to the dataframe interchange protocol specification.
- """
-
- version = 0 # version of the protocol
-
- @abstractmethod
- def __dataframe__(
- self, nan_as_null: bool = False, allow_copy: bool = True
- ) -> "DataFrame":
- """
- Construct a new exchange object, potentially changing the parameters.
-
- ``nan_as_null`` is a DEPRECATED keyword that should not be used. See warning
- below.
- ``allow_copy`` is a keyword that defines whether or not the library is
- allowed to make a copy of the data. For example, copying data would be
- necessary if a library supports strided buffers, given that this protocol
- specifies contiguous buffers.
-
- WARNING: the ``nan_as_null`` parameter will be removed from the API protocol.
- Please avoid passing it as either a positional or keyword argument. Call this
- method using ``.__dataframe__(allow_copy=...)``.
- """ # noqa: E501
- pass
-
- @property
- @abstractmethod
- def metadata(self) -> Dict[str, Any]:
- """
- The metadata for the data frame, as a dictionary with string keys. The
- contents of `metadata` may be anything, they are meant for a library
- to store information that it needs to, e.g., roundtrip losslessly or
- for two implementations to share data that is not (yet) part of the
- interchange protocol specification. For avoiding collisions with other
- entries, please add name the keys with the name of the library
- followed by a period and the desired name, e.g, ``pandas.indexcol``.
- """
- pass
-
- @abstractmethod
- def num_columns(self) -> int:
- """
- Return the number of columns in the DataFrame.
- """
- pass
-
- @abstractmethod
- def num_rows(self) -> Optional[int]:
- # TODO: not happy with Optional, but need to flag it may be expensive
- # why include it if it may be None - what do we expect consumers
- # to do here?
- """
- Return the number of rows in the DataFrame, if available.
- """
- pass
-
- @abstractmethod
- def num_chunks(self) -> int:
- """
- Return the number of chunks the DataFrame consists of.
- """
- pass
-
- @abstractmethod
- def column_names(self) -> Iterable[str]:
- """
- Return an iterator yielding the column names.
- """
- pass
-
- @abstractmethod
- def get_column(self, i: int) -> Column:
- """
- Return the column at the indicated position.
- """
- pass
-
- @abstractmethod
- def get_column_by_name(self, name: str) -> Column:
- """
- Return the column whose name is the indicated name.
- """
- pass
-
- @abstractmethod
- def get_columns(self) -> Iterable[Column]:
- """
- Return an iterator yielding the columns.
- """
- pass
-
- @abstractmethod
- def select_columns(self, indices: Sequence[int]) -> "DataFrame":
- """
- Create a new DataFrame by selecting a subset of columns by index.
- """
- pass
-
- @abstractmethod
- def select_columns_by_name(self, names: Sequence[str]) -> "DataFrame":
- """
- Create a new DataFrame by selecting a subset of columns by name.
- """
- pass
-
- @abstractmethod
- def get_chunks(
- self, n_chunks: Optional[int] = None
- ) -> Iterable["DataFrame"]:
- """
- Return an iterator yielding the chunks.
-
- By default (None), yields the chunks that the data is stored as by the
- producer. If given, ``n_chunks`` must be a multiple of
- ``self.num_chunks()``, meaning the producer must subdivide each chunk
- before yielding it.
-
- Note that the producer must ensure that all columns are chunked the
- same way.
- """
- pass
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 18f028ead9..4dc4e22887 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -26,9 +26,6 @@ from marimo._plugins.ui._impl.tables.pandas_table import (
from marimo._plugins.ui._impl.tables.polars_table import (
PolarsTableManagerFactory,
)
-from marimo._plugins.ui._impl.tables.pyarrow_table import (
- PyArrowTableManagerFactory,
-)
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
TableManager,
@@ -203,18 +200,6 @@ class DefaultTableManager(TableManager[JsonTableData]):
return PolarsTableManagerFactory.create()(
pl.DataFrame(cast(Any, self.data))
)
- if DependencyManager.pyarrow.has():
- import pyarrow as pa
-
- if isinstance(self.data, dict):
- return PyArrowTableManagerFactory.create()(
- pa.Table.from_pydict(cast(Any, self.data))
- )
- return PyArrowTableManagerFactory.create()(
- pa.Table.from_pylist(
- cast(Any, self._normalize_data(self.data))
- )
- )
raise ValueError("No supported table libraries found.")
diff --git a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
deleted file mode 100644
index 63064c364c..0000000000
--- a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
+++ /dev/null
@@ -1,179 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-from __future__ import annotations
-
-from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
-
-from marimo._data.models import ColumnSummary, ExternalDataType
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._plugins.ui._impl.tables.dataframe_protocol import (
- Column,
- DtypeKind,
-)
-from marimo._plugins.ui._impl.tables.format import FormatMapping
-from marimo._plugins.ui._impl.tables.pyarrow_table import (
- PyArrowTableManagerFactory,
-)
-from marimo._plugins.ui._impl.tables.table_manager import (
- ColumnName,
- FieldType,
- FieldTypes,
- TableManager,
-)
-from marimo._plugins.ui._impl.tables.types import (
- DataFrameLike,
- is_dataframe_like,
-)
-
-if TYPE_CHECKING:
- import pyarrow as pa # type: ignore
-
-
-class DataFrameProtocolTableManager(TableManager[DataFrameLike]):
- type = "dataframe-like"
-
- def __init__(self, data: DataFrameLike):
- self.data = data
- self._df = data.__dataframe__()
-
- if not hasattr(self._df, "num_columns"):
- raise ValueError(
- "The DataFrameLike object must have a num_columns method"
- )
-
- self._delegate: Optional[
- TableManager[Union[pa.Table, pa.RecordBatch]]
- ] = None
-
- def _ensure_delegate(
- self,
- ) -> TableManager[Union[pa.Table, pa.RecordBatch]]:
- DependencyManager.pyarrow.require(
- "for table support using the dataframe protocol"
- )
-
- if self._delegate is None:
- self._delegate = PyArrowTableManagerFactory.create()(
- arrow_table_from_dataframe_protocol(self.data)
- )
- return self._delegate
-
- def apply_formatting( # type: ignore
- self, format_mapping: FormatMapping
- ) -> Union[pa.Table, pa.RecordBatch]:
- return self._ensure_delegate().apply_formatting(format_mapping)
-
- def supports_filters(self) -> bool:
- # Does't support filters until pyarrow supports it
- return False
-
- def to_csv(self, format_mapping: Optional[FormatMapping] = None) -> bytes:
- return self._ensure_delegate().to_csv(format_mapping)
-
- def to_json(self) -> bytes:
- return self._ensure_delegate().to_json()
-
- @staticmethod
- def is_type(value: Any) -> bool:
- return is_dataframe_like(value)
-
- def select_rows(
- self, indices: list[int]
- ) -> TableManager[Union[pa.Table, pa.RecordBatch]]:
- return self._ensure_delegate().select_rows(indices)
-
- def select_columns(
- self, columns: list[str]
- ) -> TableManager[Union[pa.Table, pa.RecordBatch]]:
- return self._ensure_delegate().select_columns(columns)
-
- def get_row_headers(
- self,
- ) -> list[str]:
- return []
-
- def get_field_types(self) -> FieldTypes:
- return {
- column: self._get_field_type(self._df.get_column_by_name(column))
- for column in self._df.column_names()
- }
-
- def take(
- self, count: int, offset: int
- ) -> TableManager[Union[pa.Table, pa.RecordBatch]]:
- return self._ensure_delegate().take(count, offset)
-
- def search(self, query: str) -> TableManager[Any]:
- return self._ensure_delegate().search(query)
-
- def get_summary(self, column: str) -> ColumnSummary:
- return self._ensure_delegate().get_summary(column)
-
- def get_num_rows(self, force: bool = True) -> Optional[int]:
- if force:
- return self._df.num_rows() or int("nan")
- return None
-
- def get_num_columns(self) -> int:
- return self._df.num_columns() or int("nan")
-
- def get_column_names(self) -> list[str]:
- return list(self._df.column_names())
-
- def get_unique_column_values(
- self, column: ColumnName
- ) -> list[str | int | float]:
- return self._ensure_delegate().get_unique_column_values(column)
-
- 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) -> Tuple[FieldType, ExternalDataType]:
- kind = column.dtype[0]
- if kind == DtypeKind.BOOL:
- return ("boolean", "BOOL")
- elif kind == DtypeKind.INT:
- return ("integer", "INT")
- elif kind == DtypeKind.UINT:
- return ("integer", "UINT")
- elif kind == DtypeKind.FLOAT:
- return ("number", "FLOAT")
- elif kind == DtypeKind.STRING:
- return ("string", "STRING")
- elif kind == DtypeKind.DATETIME:
- return ("date", "DATETIME")
- elif kind == DtypeKind.CATEGORICAL:
- return ("string", "CATEGORICAL")
- else:
- return ("unknown", "UNKNOWN")
-
-
-# Copied from Altair
-# https://github.com/vega/altair/blob/18a2c3c237014591d172284560546a2f0ac1a883/altair/utils/data.py#L343
-def arrow_table_from_dataframe_protocol(
- dfi_df: DataFrameLike,
-) -> "pa.Table":
- """
- Convert a DataFrame Interchange Protocol compatible object
- to an Arrow Table
- """
- import pyarrow as pa
- import pyarrow.interchange as pi
-
- # First check if the dataframe object has a method to convert to arrow.
- # Give this preference over the pyarrow from_dataframe function
- # since the object
- # has more control over the conversion, and may have broader compatibility.
- # This is the case for Polars, which supports Date32 columns in
- # direct conversion
- # while pyarrow does not yet support this type in from_dataframe
- for convert_method_name in ("arrow", "to_arrow", "to_arrow_table"):
- convert_method = getattr(dfi_df, convert_method_name, None)
- if callable(convert_method):
- result = convert_method()
- if isinstance(result, pa.Table):
- return result
-
- return pi.from_dataframe(dfi_df) # type: ignore
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index 55afd9e52f..319d8e9416 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -17,9 +17,6 @@ from marimo._plugins.ui._impl.tables.pandas_table import (
from marimo._plugins.ui._impl.tables.polars_table import (
PolarsTableManagerFactory,
)
-from marimo._plugins.ui._impl.tables.pyarrow_table import (
- PyArrowTableManagerFactory,
-)
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
@@ -207,10 +204,6 @@ class IbisTableManagerFactory(TableManagerFactory):
return PolarsTableManagerFactory.create()(
self.data.to_polars()
)
- if DependencyManager.pyarrow.has():
- return PyArrowTableManagerFactory.create()(
- self.data.to_pyarrow()
- )
raise ValueError(
"Requires at least one of pandas, polars, or pyarrow"
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
new file mode 100644
index 0000000000..810be99b02
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -0,0 +1,276 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any, Optional, Union, cast
+
+import narwhals.stable.v1 as nw
+
+from marimo._data.models import ColumnSummary
+from marimo._plugins.ui._impl.tables.format import (
+ FormatMapping,
+ format_value,
+)
+from marimo._plugins.ui._impl.tables.table_manager import (
+ ColumnName,
+ FieldTypes,
+ TableManager,
+)
+from marimo._utils.narwhals_utils import (
+ can_narwhalify,
+ is_narwhals_integer_type,
+ is_narwhals_string_type,
+ is_narwhals_temporal_type,
+)
+
+Frame = Union[nw.DataFrame[Any], nw.LazyFrame[Any]]
+
+if TYPE_CHECKING:
+ from narwhals.typing import IntoFrame
+
+
+class NarwhalsTableManager(TableManager[Frame]):
+ type = "narwhals"
+
+ @staticmethod
+ def from_dataframe(data: IntoFrame) -> NarwhalsTableManager:
+ return NarwhalsTableManager(nw.from_native(data, strict=True))
+
+ def as_frame(self) -> nw.DataFrame[Any]:
+ if isinstance(self.data, nw.LazyFrame):
+ return self.data.collect()
+ return self.data
+
+ def to_csv(
+ self,
+ format_mapping: Optional[FormatMapping] = None,
+ ) -> bytes:
+ _data = (
+ self.apply_formatting(format_mapping)
+ if format_mapping
+ else self.as_frame()
+ )
+ csv_str = _data.write_csv()
+ if isinstance(csv_str, str):
+ return csv_str.encode("utf-8")
+ return cast(bytes, csv_str)
+
+ def to_json(self) -> bytes:
+ csv_str = self.as_frame().write_csv()
+ import csv
+
+ csv_reader = csv.DictReader(csv_str.splitlines())
+ return json.dumps([row for row in csv_reader]).encode("utf-8")
+
+ def apply_formatting(
+ self, format_mapping: FormatMapping
+ ) -> nw.DataFrame[Any]:
+ _data = self.as_frame().to_dict(as_series=False).copy()
+ for col in _data.keys():
+ if col in format_mapping:
+ _data[col] = [
+ format_value(col, x, format_mapping) for x in _data[col]
+ ]
+ return nw.from_dict(
+ _data, native_namespace=nw.get_native_namespace(self.data)
+ )
+
+ def supports_filters(self) -> bool:
+ return True
+
+ def select_rows(self, indices: list[int]) -> TableManager[Frame]:
+ df = self.as_frame()
+ return NarwhalsTableManager(df[indices])
+
+ def select_columns(self, columns: list[str]) -> TableManager[Frame]:
+ return NarwhalsTableManager(self.data.select(columns))
+
+ def get_row_headers(
+ self,
+ ) -> list[str]:
+ return []
+
+ @staticmethod
+ def is_type(value: Any) -> bool:
+ return can_narwhalify(value)
+
+ def get_field_types(self) -> FieldTypes:
+ field_types: FieldTypes = {}
+ for column, dtype in self.data.schema.items():
+ dtype_string = str(dtype)
+ if is_narwhals_string_type(dtype):
+ field_types[column] = ("string", dtype_string)
+ elif dtype == nw.Boolean:
+ field_types[column] = ("boolean", dtype_string)
+ elif is_narwhals_integer_type(dtype):
+ field_types[column] = ("integer", dtype_string)
+ elif is_narwhals_temporal_type(dtype):
+ field_types[column] = ("date", dtype_string)
+ elif dtype.is_numeric():
+ field_types[column] = ("number", dtype_string)
+ else:
+ field_types[column] = ("unknown", dtype_string)
+
+ return field_types
+
+ def take(self, count: int, offset: int) -> NarwhalsTableManager:
+ if count < 0:
+ raise ValueError("Count must be a positive integer")
+ if offset < 0:
+ raise ValueError("Offset must be a non-negative integer")
+ return NarwhalsTableManager(self.data[offset:count])
+
+ def search(self, query: str) -> TableManager[Any]:
+ query = query.lower()
+
+ expressions: list[Any] = []
+ for column in self.data.columns:
+ dtype = self.data[column].dtype
+ if dtype == nw.String:
+ expressions.append(nw.col(column).str.contains(query))
+ # TODO: Unsupported by narwhals
+ # elif dtype == nw.List(nw.String):
+ # expressions.append(
+ # nw.col(column).cast(nw.String).str.contains(query)
+ # )
+ elif (
+ dtype.is_numeric()
+ or is_narwhals_temporal_type(dtype)
+ or dtype == nw.Boolean
+ ):
+ expressions.append(
+ nw.col(column).cast(nw.String).str.contains(f"(?i){query}")
+ )
+
+ if not expressions:
+ return NarwhalsTableManager(self.data.filter(nw.lit(False)))
+
+ or_expr = expressions[0]
+ for expr in expressions[1:]:
+ or_expr = or_expr | expr
+
+ filtered = self.data.filter(or_expr)
+ return NarwhalsTableManager(filtered)
+
+ def get_summary(self, column: str) -> ColumnSummary:
+ summary = self._get_summary_internal(column)
+ for key, value in summary.__dict__.items():
+ if value is not None:
+ summary.__dict__[key] = _maybe_convert_as_py(value)
+ return summary
+
+ 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.columns:
+ return ColumnSummary()
+ col = self.data[column]
+ total = len(col)
+ if is_narwhals_string_type(col.dtype):
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ unique=col.n_unique(),
+ )
+ if col.dtype == nw.Boolean:
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ true=cast(int, col.sum()),
+ false=cast(int, total - col.sum()),
+ )
+ if col.dtype == nw.Date:
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ min=col.min(),
+ max=col.max(),
+ mean=col.mean(),
+ # TODO: Implement median not in narwhals
+ # median=col.median(),
+ )
+ if is_narwhals_temporal_type(col.dtype):
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ min=col.min(),
+ max=col.max(),
+ mean=col.mean(),
+ # TODO: Implement median not in narwhals
+ # median=col.median(),
+ p5=col.quantile(0.05, interpolation="nearest"),
+ p25=col.quantile(0.25, interpolation="nearest"),
+ p75=col.quantile(0.75, interpolation="nearest"),
+ p95=col.quantile(0.95, interpolation="nearest"),
+ )
+ if col.dtype == nw.List:
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ )
+ if col.dtype == nw.Unknown:
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ )
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ unique=col.n_unique()
+ if is_narwhals_integer_type(col.dtype)
+ else None,
+ min=col.min(),
+ max=col.max(),
+ mean=col.mean(),
+ # TODO: Implement median not in narwhals
+ # median=col.median(),
+ std=col.std(),
+ p5=col.quantile(0.05, interpolation="nearest"),
+ p25=col.quantile(0.25, interpolation="nearest"),
+ p75=col.quantile(0.75, interpolation="nearest"),
+ p95=col.quantile(0.95, interpolation="nearest"),
+ )
+
+ def get_num_rows(self, force: bool = True) -> Optional[int]:
+ # If force is true, collect the data and get the number of rows
+ if force:
+ return self.as_frame().shape[0]
+
+ # When lazy, we don't know the number of rows
+ if isinstance(self.data, nw.LazyFrame):
+ return None
+
+ # Otherwise, we can get the number of rows from the shape
+ return self.data.shape[0]
+
+ def get_num_columns(self) -> int:
+ return len(self.data.columns)
+
+ def get_column_names(self) -> list[str]:
+ return self.data.columns
+
+ def get_unique_column_values(self, column: str) -> list[str | int | float]:
+ return self.data[column].unique().to_list()
+
+ def sort_values(
+ self, by: ColumnName, descending: bool
+ ) -> NarwhalsTableManager:
+ sorted_data = self.data.sort(by, descending=descending)
+ return NarwhalsTableManager(sorted_data)
+
+ def __repr__(self) -> str:
+ rows = self.get_num_rows(force=False)
+ columns = self.get_num_columns()
+ df_type = str(nw.get_native_namespace(self.data).__name__)
+ if rows is None:
+ return f"{df_type}: {columns:,} columns"
+ return f"{df_type}: {rows:,} rows x {columns:,} columns"
+
+
+# pyarrow use wrapper types for primitives
+# so we need to convert to the primitive type
+def _maybe_convert_as_py(value: Any) -> Any:
+ if hasattr(value, "to_pylist"):
+ return value.to_pylist()
+ if hasattr(value, "as_py"):
+ return value.as_py()
+ return value
diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
deleted file mode 100644
index 8ce236dbaf..0000000000
--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
+++ /dev/null
@@ -1,298 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-from __future__ import annotations
-
-import io
-from typing import Any, Optional, Tuple, Union, cast
-
-from marimo._data.models import ColumnSummary, ExternalDataType
-from marimo._plugins.ui._impl.tables.format import (
- FormatMapping,
- format_value,
-)
-from marimo._plugins.ui._impl.tables.table_manager import (
- ColumnName,
- FieldType,
- FieldTypes,
- TableManager,
- TableManagerFactory,
-)
-
-
-class PyArrowTableManagerFactory(TableManagerFactory):
- @staticmethod
- def package_name() -> str:
- return "pyarrow"
-
- @staticmethod
- def create() -> type[TableManager[Any]]:
- import pyarrow as pa # type: ignore
- import pyarrow.compute as pc # type: ignore
-
- class PyArrowTableManager(
- TableManager[Union[pa.Table, pa.RecordBatch]]
- ):
- type = "pyarrow"
-
- def to_csv(
- self, format_mapping: Optional[FormatMapping] = None
- ) -> bytes:
- import pyarrow.csv as csv # type: ignore
-
- _data = self.data
- if format_mapping:
- _data = self.apply_formatting(format_mapping)
- buffer = io.BytesIO()
- csv.write_csv(_data, buffer)
- return buffer.getvalue()
-
- def to_json(self) -> bytes:
- # Arrow does not have a built-in JSON writer
- return (
- self.data.to_pandas()
- .to_json(orient="records")
- .encode("utf-8")
- )
-
- def apply_formatting(
- self, format_mapping: FormatMapping
- ) -> Union[pa.Table, pa.RecordBatch]:
- _data = self.data
- if isinstance(_data, pa.Table):
- column_names = _data.column_names
- else: # pa.RecordBatch
- column_names = _data.schema.names
-
- transformed_columns: list[pa.Array[Any]] = []
- for i, col in enumerate(column_names):
- transformed_column: pa.Array[Any]
- if isinstance(_data, pa.Table):
- transformed_column = _data.column(i).chunks[0]
- else:
- transformed_column = _data.column(i)
- if col in format_mapping:
- transformed_values: list[Any] = [
- format_value(col, value.as_py(), format_mapping)
- for value in transformed_column
- ]
- formatted_type = cast(
- Any, pa.array(transformed_values)
- ).type
- transformed_column = pa.array(
- transformed_values, type=formatted_type
- ) # type: ignore
-
- # Raise ValueError if transformed_column is pa.ChunkedArray
- if isinstance(transformed_column, pa.ChunkedArray):
- raise ValueError(
- f"Column {col} is a ChunkedArray, "
- "which is not supported."
- )
-
- transformed_columns.append(transformed_column)
-
- if isinstance(_data, pa.Table):
- _data = pa.table(
- cast(Any, transformed_columns), names=column_names
- )
- else: # pa.RecordBatch
- new_schema = pa.schema(
- [
- pa.field(
- col,
- cast(Any, transformed_columns[i]).type,
- )
- for i, col in enumerate(column_names)
- ]
- )
- _data = pa.record_batch(
- transformed_columns, schema=new_schema
- )
-
- return _data
-
- def select_rows(self, indices: list[int]) -> PyArrowTableManager:
- if not indices:
- return PyArrowTableManager(
- pa.Table.from_pylist([], schema=self.data.schema)
- )
- return PyArrowTableManager(self.data.take(indices))
-
- def supports_filters(self) -> bool:
- # Does't support filters until we
- # have a PyArrowTransformHandler
- return False
-
- def select_columns(
- self, columns: list[str]
- ) -> PyArrowTableManager:
- if isinstance(self.data, pa.RecordBatch):
- return PyArrowTableManager(
- pa.record_batch(
- [
- self.data.column(
- self.data.schema.get_field_index(col)
- )
- for col in columns
- ],
- names=columns,
- )
- )
- return PyArrowTableManager(self.data.select(columns))
-
- def get_row_headers(
- self,
- ) -> list[str]:
- return []
-
- @staticmethod
- def is_type(value: Any) -> bool:
- import pyarrow as pa # type: ignore
-
- return isinstance(value, pa.Table) or isinstance(
- value, pa.RecordBatch
- )
-
- def get_field_types(self) -> FieldTypes:
- return {
- column: PyArrowTableManager._get_field_type(
- cast(Any, self.data.column(idx))
- )
- for idx, column in enumerate(self.data.schema.names)
- }
-
- def take(self, count: int, offset: int) -> PyArrowTableManager:
- if count < 0:
- raise ValueError("Count must be a positive integer")
- if offset < 0:
- raise ValueError("Offset must be a non-negative integer")
- if offset >= self.data.num_rows:
- return PyArrowTableManager(
- pa.Table.from_pylist([], schema=self.data.schema)
- )
- end = min(offset + count, self.data.num_rows)
- return PyArrowTableManager(
- self.data.slice(offset, end - offset)
- )
-
- def search(self, query: str) -> TableManager[Any]:
- query = query.lower()
- import pyarrow.compute as pc
-
- masks: list[Any] = []
- for column in self.data.columns: # type: ignore
- # Cast to string to handle non-string columns
- column = pc.cast(column, pa.string()) # type: ignore
- mask: pa.BooleanArray = pc.match_substring( # type: ignore
- column, # type: ignore
- query,
- ignore_case=True,
- )
- masks.append(mask)
-
- # Combine the masks using logical OR
- combined_mask: pa.BooleanArray = masks[0]
- for mask in masks[1:]:
- combined_mask = pc.or_(combined_mask, mask) # type: ignore
- return PyArrowTableManager(self.data.filter(combined_mask))
-
- def get_summary(self, column: str) -> ColumnSummary:
- # If column is not in the dataframe, return an empty summary
- if column not in self.data.schema.names:
- return ColumnSummary()
- idx = self.data.schema.get_field_index(column)
- col: Any = self.data.column(idx)
-
- field_type = self._get_field_type(col)[0]
- if field_type == "unknown":
- return ColumnSummary()
- if field_type == "string":
- return ColumnSummary(
- total=self.data.num_rows,
- nulls=col.null_count,
- unique=pc.count_distinct(col).as_py(), # type: ignore[attr-defined]
- )
- if field_type == "boolean":
- return ColumnSummary(
- total=self.data.num_rows,
- nulls=col.null_count,
- true=pc.sum(col).as_py(), # type: ignore[attr-defined]
- false=self.data.num_rows
- - pc.sum(col).as_py() # type: ignore[attr-defined]
- - col.null_count,
- )
- if field_type == "integer":
- return ColumnSummary(
- total=self.data.num_rows,
- nulls=col.null_count,
- unique=pc.count_distinct(col).as_py(), # type: ignore[attr-defined]
- min=pc.min(col).as_py(), # type: ignore[attr-defined]
- max=pc.max(col).as_py(), # type: ignore[attr-defined]
- mean=pc.mean(col).as_py(), # type: ignore[attr-defined]
- )
- if field_type == "number":
- return ColumnSummary(
- total=self.data.num_rows,
- nulls=col.null_count,
- min=pc.min(col).as_py(), # type: ignore[attr-defined]
- max=pc.max(col).as_py(), # type: ignore[attr-defined]
- mean=pc.mean(col).as_py(), # type: ignore[attr-defined]
- )
- if field_type == "date":
- return ColumnSummary(
- total=self.data.num_rows,
- nulls=col.null_count,
- min=pc.min(col).as_py(), # type: ignore[attr-defined]
- max=pc.max(col).as_py(), # type: ignore[attr-defined]
- )
- return ColumnSummary()
-
- def get_num_rows(self, force: bool = True) -> int:
- del force
- return self.data.num_rows
-
- def get_num_columns(self) -> int:
- return self.data.num_columns
-
- def get_column_names(self) -> list[str]:
- return self.data.schema.names
-
- def get_unique_column_values(
- self, column: str
- ) -> list[str | int | float]:
- idx = self.data.schema.get_field_index(column)
- col: Any = self.data.column(idx)
- return pc.unique(col).to_pylist() # type: ignore[attr-defined, no-any-return]
-
- def sort_values(
- self, by: ColumnName, descending: bool
- ) -> PyArrowTableManager:
- sorted_data = self.data.sort_by( # type: ignore
- [(by, "ascending" if not descending else "descending")]
- )
- return PyArrowTableManager(sorted_data)
-
- @staticmethod
- def _get_field_type(
- column: pa.ChunkedArray[Any],
- ) -> Tuple[FieldType, ExternalDataType]:
- dtype_string = str(column.type)
- if isinstance(column, pa.NullArray):
- return ("unknown", dtype_string)
- elif pa.types.is_string(column.type):
- return ("string", dtype_string)
- elif pa.types.is_boolean(column.type):
- return ("boolean", dtype_string)
- elif pa.types.is_integer(column.type):
- return ("integer", dtype_string)
- elif pa.types.is_floating(column.type) or pa.types.is_decimal(
- column.type
- ):
- return ("number", dtype_string)
- elif pa.types.is_date(column.type) or pa.types.is_timestamp(
- column.type
- ):
- return ("date", dtype_string)
- else:
- return ("unknown", dtype_string)
-
- return PyArrowTableManager
diff --git a/marimo/_plugins/ui/_impl/tables/types.py b/marimo/_plugins/ui/_impl/tables/types.py
deleted file mode 100644
index 1af73d6383..0000000000
--- a/marimo/_plugins/ui/_impl/tables/types.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-from __future__ import annotations
-
-from typing import Protocol
-
-from marimo._plugins.ui._impl.tables.dataframe_protocol import DataFrame
-
-
-class DataFrameLike(Protocol):
- def __dataframe__(
- self, nan_as_null: bool = False, allow_copy: bool = True
- ) -> DataFrame: ...
-
-
-def is_dataframe_like(value: object) -> bool:
- return (
- hasattr(value, "__dataframe__")
- and callable(value.__dataframe__)
- # By checking these are equal, we likely guarding against
- # __getattr__ implementations that may return different callables
- and value.__dataframe__ == value.__dataframe__
- # We don't want to call __dataframe__, in case it has side effects
- )
diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.py
index e34325a361..03ef4fb8b5 100644
--- a/marimo/_plugins/ui/_impl/tables/utils.py
+++ b/marimo/_plugins/ui/_impl/tables/utils.py
@@ -5,31 +5,23 @@ from typing import Any, List
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.default_table import DefaultTableManager
-from marimo._plugins.ui._impl.tables.df_protocol_table import (
- DataFrameProtocolTableManager,
-)
from marimo._plugins.ui._impl.tables.ibis_table import IbisTableManagerFactory
+from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManager
from marimo._plugins.ui._impl.tables.pandas_table import (
PandasTableManagerFactory,
)
from marimo._plugins.ui._impl.tables.polars_table import (
PolarsTableManagerFactory,
)
-from marimo._plugins.ui._impl.tables.pyarrow_table import (
- PyArrowTableManagerFactory,
-)
from marimo._plugins.ui._impl.tables.table_manager import (
TableManager,
TableManagerFactory,
)
-from marimo._plugins.ui._impl.tables.types import (
- is_dataframe_like,
-)
+from marimo._utils.narwhals_utils import can_narwhalify
MANAGERS: List[TableManagerFactory] = [
PandasTableManagerFactory(),
PolarsTableManagerFactory(),
- PyArrowTableManagerFactory(),
IbisTableManagerFactory(),
]
@@ -52,18 +44,8 @@ def get_table_manager_or_none(data: Any) -> TableManager[Any] | None:
if manager.is_type(data):
return manager(data)
- # Unpack narwhal dataframe wrapper
- if DependencyManager.narwhals.imported():
- import narwhals
-
- if isinstance(data, narwhals.DataFrame):
- return get_table_manager_or_none(narwhals.to_native(data))
-
- # If we have a DataFrameLike object, use the DataFrameProtocolTableManager
- if is_dataframe_like(data):
- try:
- return DataFrameProtocolTableManager(data)
- except Exception:
- return None
+ # Fallback to generic NarwhalsTableManager
+ if can_narwhalify(data):
+ return NarwhalsTableManager.from_dataframe(data)
return None
diff --git a/marimo/_smoke_tests/dataframe.py b/marimo/_smoke_tests/dataframe.py
index c346b0c189..5c0a9cd0ac 100644
--- a/marimo/_smoke_tests/dataframe.py
+++ b/marimo/_smoke_tests/dataframe.py
@@ -14,7 +14,7 @@
import marimo
-__generated_with = "0.8.14"
+__generated_with = "0.9.10"
app = marimo.App(width="full")
@@ -32,7 +32,7 @@ def __(mo):
]
as_list = mo.ui.table(_data)
as_list
- return as_list,
+ return (as_list,)
@app.cell
@@ -50,7 +50,7 @@ def __(mo):
}
as_dict = mo.ui.table(_data)
as_dict
- return as_dict,
+ return (as_dict,)
@app.cell
@@ -64,7 +64,7 @@ def __(mo):
_data = [1, 2, "hello", False]
as_primitives = mo.ui.table(_data)
as_primitives
- return as_primitives,
+ return (as_primitives,)
@app.cell
@@ -89,7 +89,7 @@ def __(mo):
def __(cars, mo):
dataframe = mo.ui.dataframe(cars)
dataframe
- return dataframe,
+ return (dataframe,)
@app.cell(hide_code=True)
@@ -150,7 +150,7 @@ def __(mo):
def __(mo, pl_dataframe):
pl_dataframe_prime = mo.ui.dataframe(pl_dataframe)
pl_dataframe_prime
- return pl_dataframe_prime,
+ return (pl_dataframe_prime,)
@app.cell
@@ -169,7 +169,7 @@ def __(mo):
def __(cars, mo, pl):
pl_dataframe = pl.DataFrame(cars)
mo.ui.table(pl_dataframe, selection=None)
- return pl_dataframe,
+ return (pl_dataframe,)
@app.cell(hide_code=True)
@@ -194,7 +194,7 @@ def __(mo):
def __(cars, mo, pa):
arrow_table = pa.Table.from_pandas(cars)
mo.accordion({"Details": mo.plain_text(arrow_table)})
- return arrow_table,
+ return (arrow_table,)
@app.cell(hide_code=True)
@@ -207,7 +207,7 @@ def __(mo):
def __(arrow_table, mo):
arrow_table_el = mo.ui.table(arrow_table)
arrow_table_el
- return arrow_table_el,
+ return (arrow_table_el,)
@app.cell(hide_code=True)
@@ -242,12 +242,13 @@ def __(mo):
@app.cell
def __():
import dask.dataframe as dd
+ import requests
dask_df = dd.read_csv(
"https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
)
dask_df
- return dask_df, dd
+ return dask_df, dd, requests
@app.cell
@@ -274,7 +275,7 @@ def __(mo):
def __(ibis_data, mo):
ibis_penguins = mo.ui.table(ibis_data)
ibis_penguins
- return ibis_penguins,
+ return (ibis_penguins,)
@app.cell
diff --git a/marimo/_smoke_tests/tables/ibis_example.py b/marimo/_smoke_tests/tables/ibis_example.py
index 7d6fef992b..a27962a590 100644
--- a/marimo/_smoke_tests/tables/ibis_example.py
+++ b/marimo/_smoke_tests/tables/ibis_example.py
@@ -1,20 +1,19 @@
import marimo
-__generated_with = "0.8.15"
+__generated_with = "0.9.10"
app = marimo.App(width="medium")
@app.cell
def __():
import marimo as mo
- return mo,
+ return (mo,)
@app.cell
def __(mo):
import ibis
- # hover:bg-muted/50 data-[state=selected]:bg-muted
memtable = ibis.memtable(
{
"rowid": range(3000),
diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.py
index 411d3b3491..7dada53f31 100644
--- a/marimo/_utils/narwhals_utils.py
+++ b/marimo/_utils/narwhals_utils.py
@@ -19,8 +19,8 @@ def empty_df(native_df: IntoFrame) -> IntoFrame:
"""
Get an empty dataframe with the same schema as the given dataframe.
"""
- if can_narwhalify(native_df):
- df = nw.from_native(native_df, eager_or_interchange_only=True)
+ if can_narwhalify(native_df, eager_only=True):
+ df = nw.from_native(native_df, eager_only=True)
return df[[]].to_native()
return native_df
@@ -41,14 +41,14 @@ def assert_narwhals_series(series: nw.Series) -> None:
raise ValueError(f"Unsupported series type. Got {type(series)}")
-def can_narwhalify(obj: Any) -> TypeGuard[IntoFrame]:
+def can_narwhalify(obj: Any, eager_only: bool = False) -> TypeGuard[IntoFrame]:
"""
Check if the given object can be narwhalified.
"""
if obj is None:
return False
try:
- nw.from_native(obj, strict=True)
+ nw.from_native(obj, strict=True, eager_only=eager_only) # type: ignore[call-overload]
return True
except TypeError:
return False
@@ -60,3 +60,64 @@ def assert_can_narwhalify(obj: Any) -> TypeGuard[IntoFrame]:
"""
nw.from_native(obj)
return True
+
+
+def dataframe_to_csv(df: IntoFrame) -> str:
+ """
+ Convert a dataframe to a CSV string.
+ """
+ assert_can_narwhalify(df)
+ df = nw.from_native(df, strict=True)
+ if isinstance(df, nw.LazyFrame):
+ return str(df.collect().write_csv())
+ else:
+ return str(df.write_csv())
+
+
+def is_narwhals_integer_type(
+ dtype: Any,
+) -> TypeGuard[
+ nw.Int64
+ | nw.UInt64
+ | nw.Int32
+ | nw.UInt32
+ | nw.Int16
+ | nw.UInt16
+ | nw.Int8
+ | nw.UInt8
+]:
+ """
+ Check if the given dtype is integer type.
+ """
+ return bool(
+ dtype == nw.Int64
+ or dtype == nw.UInt64
+ or dtype == nw.Int32
+ or dtype == nw.UInt32
+ or dtype == nw.Int16
+ or dtype == nw.UInt16
+ or dtype == nw.Int8
+ or dtype == nw.UInt8
+ )
+
+
+def is_narwhals_temporal_type(
+ dtype: Any,
+) -> TypeGuard[nw.Datetime | nw.Date | nw.Duration | nw.Duration]:
+ """
+ Check if the given dtype is temporal type.
+ """
+ return bool(
+ dtype == nw.Datetime or dtype == nw.Date or dtype == nw.Duration
+ )
+
+
+def is_narwhals_string_type(
+ dtype: Any,
+) -> TypeGuard[nw.String | nw.Categorical | nw.Enum]:
+ """
+ Check if the given dtype is string type.
+ """
+ return bool(
+ dtype == nw.String or dtype == nw.Categorical or dtype == nw.Enum
+ )
diff --git a/tests/_data/mocks.py b/tests/_data/mocks.py
index 66544978f4..34adb023c6 100644
--- a/tests/_data/mocks.py
+++ b/tests/_data/mocks.py
@@ -8,7 +8,7 @@ from marimo._dependencies.dependencies import DependencyManager
if TYPE_CHECKING:
from narwhals.typing import IntoDataFrame
-DFType = Literal["pandas", "polars", "ibis"]
+DFType = Literal["pandas", "polars", "ibis", "pyarrow"]
def create_dataframes(
@@ -47,6 +47,11 @@ def create_dataframes(
dfs.append(ibis.memtable(data))
+ if DependencyManager.pyarrow.has() and should_include("pyarrow"):
+ import pyarrow as pa
+
+ dfs.append(pa.Table.from_pydict(data))
+
return dfs
diff --git a/tests/_data/test_series.py b/tests/_data/test_series.py
index 1bf73fc65e..22b45ae961 100644
--- a/tests/_data/test_series.py
+++ b/tests/_data/test_series.py
@@ -20,6 +20,8 @@ HAS_DEPS = (
and DependencyManager.polars.has()
)
+# We exclude ibis because it neither eager_or_interchange_only
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
@@ -35,7 +37,7 @@ def test_number_series(
assert response.min == 1
assert response.max == 3
- assert response.label == "A"
+ assert response.label == "A" or is_pyarrow_type(df)
with pytest.raises(ValueError):
response = get_number_series_info(df["B"])
@@ -62,11 +64,11 @@ def test_categorical_series(df: Any) -> None:
response = get_category_series_info(df["B"])
assert response.categories == ["a", "b"]
- assert response.label == "B"
+ assert response.label == "B" or is_pyarrow_type(df)
response = get_category_series_info(df["A"])
assert response.categories == [1, 2, 3]
- assert response.label == "A"
+ assert response.label == "A" or is_pyarrow_type(df)
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@@ -90,7 +92,7 @@ def test_date_series(df: Any) -> None:
assert response.min == "2024-01-01"
assert response.max == "2024-01-03"
- assert response.label == "C"
+ assert response.label == "C" or is_pyarrow_type(df)
with pytest.raises(ValueError):
response = get_date_series_info(df["B"])
@@ -119,7 +121,7 @@ def test_datetime_series(df: Any) -> None:
assert response.min == "2024-01-01T12:00:00"
assert response.max == "2024-01-03T15:45:00"
- assert response.label == "C"
+ assert response.label == "C" or is_pyarrow_type(df)
with pytest.raises(ValueError):
response = get_datetime_series_info(df["B"])
@@ -152,3 +154,13 @@ def test_ibis_fails(df: Any) -> None:
get_date_series_info(df["C"])
with pytest.raises(ValueError):
get_datetime_series_info(df["C"])
+
+
+# Pyarrow columns don't have a name
+def is_pyarrow_type(response: Any) -> bool:
+ try:
+ import pyarrow as pa
+
+ return isinstance(response, pa.Table)
+ except ImportError:
+ return False
diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
index d719073595..694e38460a 100644
--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import base64
+import datetime
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
@@ -15,23 +17,22 @@ from marimo._plugins.ui._impl.charts.altair_transformer import (
_to_marimo_json,
register_transformers,
)
-
-if TYPE_CHECKING:
- import pandas as pd
+from marimo._utils.narwhals_utils import dataframe_to_csv
+from tests._data.mocks import create_dataframes
HAS_DEPS = DependencyManager.pandas.has() and DependencyManager.altair.has()
-
-def get_data() -> pd.DataFrame:
- import pandas as pd
-
- return pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+if TYPE_CHECKING:
+ from narwhals.typing import IntoDataFrame
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
-def test_to_marimo_json():
- sample_data = get_data()
- result = _to_marimo_json(sample_data)
+ "df",
+ create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),
+)
+def test_to_marimo_json(df: IntoDataFrame):
+ result = _to_marimo_json(df)
assert isinstance(result, dict)
assert "url" in result
@@ -40,9 +41,12 @@ def test_to_marimo_json():
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
-def test_to_marimo_csv():
- sample_data = get_data()
- result = _to_marimo_csv(sample_data)
+ "df",
+ create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),
+)
+def test_to_marimo_csv(df: IntoDataFrame):
+ result = _to_marimo_csv(df)
assert isinstance(result, dict)
assert "url" in result
@@ -51,9 +55,12 @@ def test_to_marimo_csv():
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
-def test_to_marimo_inline_csv():
- sample_data = get_data()
- result = _to_marimo_inline_csv(sample_data)
+ "df",
+ create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),
+)
+def test_to_marimo_inline_csv(df: IntoDataFrame):
+ result = _to_marimo_inline_csv(df)
assert isinstance(result, dict)
assert "url" in result
@@ -63,9 +70,12 @@ def test_to_marimo_inline_csv():
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
-def test_data_to_json_string():
- sample_data = get_data()
- result = _data_to_json_string(sample_data)
+ "df",
+ create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),
+)
+def test_data_to_json_string(df: IntoDataFrame):
+ result = _data_to_json_string(df)
assert isinstance(result, str)
parsed = json.loads(result)
@@ -74,9 +84,15 @@ def test_data_to_json_string():
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
-def test_data_to_csv_string():
- sample_data = get_data()
- result = _data_to_csv_string(sample_data)
+ "df",
+ # We skip pyarrow because it's csv is formatted differently
+ create_dataframes(
+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["pyarrow"]
+ ),
+)
+def test_data_to_csv_string(df: IntoDataFrame):
+ result = _data_to_csv_string(df)
assert isinstance(result, str)
lines = result.strip().split("\n")
@@ -84,6 +100,107 @@ def test_data_to_csv_string():
assert lines[0] == "A,B" or lines[0] == "A,B\r"
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes({}, exclude=["ibis"]),
+)
+def test_to_marimo_json_empty_dataframe(df: IntoDataFrame):
+ result = _to_marimo_json(df)
+
+ assert isinstance(result, dict)
+ assert "url" in result
+ assert "format" in result
+ assert result["format"] == {"type": "json"}
+ assert result["url"].startswith("data:application/json;base64,")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"A": [1, 1, 3], "B": ["a", None, "c"], "C": [True, False, None]}
+ ),
+)
+def test_to_marimo_csv_with_missing_values(df: IntoDataFrame):
+ result = _to_marimo_csv(df)
+
+ assert isinstance(result, dict)
+ assert "url" in result
+ assert "format" in result
+ assert result["format"] == {"type": "csv"}
+ assert result["url"].startswith("data:text/csv;base64,")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"A": list(range(10000)), "B": [f"value_{i}" for i in range(10000)]},
+ exclude=["pyarrow"],
+ ),
+)
+def test_to_marimo_inline_csv_large_dataset(df: IntoDataFrame):
+ result = _to_marimo_inline_csv(df)
+
+ assert isinstance(result, dict)
+ assert "url" in result
+ assert result["url"].startswith("data:text/csv;base64,")
+ assert "format" in result
+ assert result["format"] == {"type": "csv"}
+
+ # Verify the content of the inline CSV
+ base64_data = result["url"].split(",")[1]
+ decoded_data = base64.b64decode(base64_data).decode("utf-8")
+ assert decoded_data.startswith("A,B\n0,value_0\n1,value_1\n")
+ assert decoded_data.endswith("9998,value_9998\n9999,value_9999\n")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ # We skip pyarrow because it's json is missing new lines
+ create_dataframes(
+ {"A": [1, 2, 3], "B": ['a"b', "c,d", "e\nf"]}, exclude=["pyarrow"]
+ ),
+)
+def test_data_to_json_string_with_special_characters(
+ df: IntoDataFrame,
+):
+ result = _data_to_json_string(df)
+
+ assert isinstance(result, str)
+ parsed = json.loads(result)
+ assert len(parsed) == 3
+ assert parsed[0]["B"] == 'a"b'
+ assert parsed[1]["B"] == "c,d"
+ assert parsed[2]["B"] == "e\nf"
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {
+ "int": [1, 2, 3],
+ "float": [1.1, 2.2, 3.3],
+ "bool": [True, False, True],
+ "datetime": [
+ datetime.datetime(2023, 1, 1),
+ datetime.datetime(2023, 1, 2),
+ datetime.datetime(2023, 1, 3),
+ ],
+ "category": ["a", "b", "c"],
+ },
+ exclude=["ibis"],
+ ),
+)
+def test_data_to_csv_string_with_different_dtypes(df: IntoDataFrame):
+ result = _data_to_csv_string(df)
+ assert isinstance(result, str)
+ assert result == dataframe_to_csv(df)
+
+
@patch("altair.data_transformers")
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
def test_register_transformers(mock_data_transformers: MagicMock):
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json
new file mode 100644
index 0000000000..2e1f7ef460
--- /dev/null
+++ b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json
@@ -0,0 +1,14 @@
+{
+ "strings": ["string", "String"],
+ "bool": ["boolean", "Boolean"],
+ "int": ["integer", "Int64"],
+ "float": ["number", "Float64"],
+ "datetime": ["date", "Datetime(time_unit='us', time_zone=None)"],
+ "struct": ["unknown", "Struct"],
+ "list": ["unknown", "List(Int64)"],
+ "array": ["unknown", "List(Int64)"],
+ "nulls": ["string", "String"],
+ "categorical": ["string", "Categorical"],
+ "duration": ["date", "Duration(time_unit='us')"],
+ "mixed_list": ["unknown", "List(String)"]
+}
diff --git a/tests/_plugins/ui/_impl/tables/test_df_protocol.py b/tests/_plugins/ui/_impl/tables/test_df_protocol.py
deleted file mode 100644
index ca5aaebf03..0000000000
--- a/tests/_plugins/ui/_impl/tables/test_df_protocol.py
+++ /dev/null
@@ -1,238 +0,0 @@
-from __future__ import annotations
-
-import datetime
-import unittest
-from typing import cast
-
-import pytest
-
-from marimo._data.models import ColumnSummary
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._plugins.ui._impl.tables.df_protocol_table import (
- DataFrameProtocolTableManager,
-)
-from marimo._plugins.ui._impl.tables.types import DataFrameLike
-
-HAS_DEPS = DependencyManager.pyarrow.has()
-
-
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-class TestDataFrameProtocolTableManager(unittest.TestCase):
- def setUp(self) -> None:
- import pyarrow as pa
-
- self.data = pa.table(
- { # type: ignore
- # Integer
- "A": [1, 2, 3],
- # String
- "B": ["a", "b", "c"],
- # Float
- "C": [1.0, 2.0, 3.0],
- # Boolean
- "D": [True, False, True],
- # DateTime
- "E": [
- datetime.datetime(2021, 1, 1),
- datetime.datetime(2021, 1, 2),
- datetime.datetime(2021, 1, 3),
- ],
- }
- )
- self.manager = DataFrameProtocolTableManager(
- cast(DataFrameLike, self.data)
- )
-
- def test_to_csv(self) -> None:
- assert isinstance(self.manager.to_csv(), bytes)
-
- def test_to_json(self) -> None:
- assert isinstance(self.manager.to_json(), bytes)
-
- def test_select_rows(self) -> None:
- indices = [0, 2]
- selected_manager = self.manager.select_rows(indices)
- expected_data = self.data.take(indices)
- assert selected_manager.data == expected_data
-
- def test_select_rows_empty(self) -> None:
- selected_manager = self.manager.select_rows([])
- assert selected_manager.data.num_rows == 0
-
- def test_select_columns(self) -> None:
- columns = ["A"]
- selected_manager = self.manager.select_columns(columns)
- expected_data = self.data.select(columns)
- assert selected_manager.data == expected_data
-
- def test_get_row_headers(self) -> None:
- expected_headers = []
- assert self.manager.get_row_headers() == expected_headers
-
- def test_is_type(self) -> None:
- assert self.manager.is_type(self.data)
- assert not self.manager.is_type("not a dataframe")
-
- def test_get_field_types(self) -> None:
- import pyarrow as pa
-
- expected_field_types = {
- "A": ("integer", "INT"),
- "B": ("string", "STRING"),
- "C": ("number", "FLOAT"),
- "D": ("boolean", "BOOL"),
- "E": ("date", "DATETIME"),
- }
- assert self.manager.get_field_types() == expected_field_types
-
- complex_data = pa.table(
- {
- "A": [1, 2, 3],
- "B": ["a", "b", "c"],
- "C": [1.0, 2.0, 3.0],
- "D": [True, False, True],
- } # type: ignore
- )
- expected_field_types = {
- "A": ("integer", "INT"),
- "B": ("string", "STRING"),
- "C": ("number", "FLOAT"),
- "D": ("boolean", "BOOL"),
- }
- assert (
- DataFrameProtocolTableManager(
- cast(DataFrameLike, complex_data)
- ).get_field_types()
- == expected_field_types
- )
-
- def test_limit(self) -> None:
- limited_manager = self.manager.take(1, 0)
- expected_data = self.data.take([0])
- assert limited_manager.data == expected_data
-
- def test_take_out_of_bounds(self) -> None:
- # Too large of page
- assert self.manager.take(10, 0).data == self.data
-
- # Too large of page and offset
- assert len(self.manager.take(10, 10).data) == 0
-
- def test_summary_integer(self) -> None:
- column = "A"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- unique=3,
- min=1,
- max=3,
- mean=2.0,
- )
-
- def test_summary_string(self) -> None:
- column = "B"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- unique=3,
- )
-
- def test_summary_number(self) -> None:
- column = "C"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- min=1.0,
- max=3.0,
- mean=2.0,
- )
-
- def test_summary_boolean(self) -> None:
- column = "D"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- true=2,
- false=1,
- )
-
- def test_summary_date(self) -> None:
- column = "E"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- min=datetime.datetime(2021, 1, 1, 0, 0),
- max=datetime.datetime(2021, 1, 3, 0, 0),
- )
-
- def test_apply_formatting(self) -> None:
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- "B": lambda x: x.upper(),
- "C": lambda x: f"{x:.2f}",
- "D": lambda x: not x,
- "E": lambda x: x.strftime("%Y-%m-%d"),
- }
- formatted_data = self.manager.apply_formatting(format_mapping)
- expected_data = pa.table(
- {
- "A": [2, 4, 6],
- "B": ["A", "B", "C"],
- "C": ["1.00", "2.00", "3.00"],
- "D": [False, True, False],
- "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
- }
- )
- assert formatted_data.equals(expected_data)
-
- def test_apply_formatting_partial(self) -> None:
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- }
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- expected_data = pa.table(
- {
- "A": [2, 4, 6],
- "B": ["a", "b", "c"],
- "C": [1.0, 2.0, 3.0],
- "D": [True, False, True],
- "E": [
- datetime.datetime(2021, 1, 1),
- datetime.datetime(2021, 1, 2),
- datetime.datetime(2021, 1, 3),
- ],
- }
- )
- assert formatted_data.equals(expected_data)
-
- def test_apply_formatting_empty(self) -> None:
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {}
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- assert formatted_data.equals(self.data)
-
- def test_apply_formatting_invalid_column(self) -> None:
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "Z": lambda x: x * 2,
- }
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- assert formatted_data.equals(self.data)
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
new file mode 100644
index 0000000000..4d3a063c5c
--- /dev/null
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -0,0 +1,641 @@
+from __future__ import annotations
+
+import datetime
+import json
+import unittest
+from typing import Any
+
+import pytest
+
+from marimo._data.models import ColumnSummary
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.ui._impl.tables.format import FormatMapping
+from marimo._plugins.ui._impl.tables.narwhals_table import (
+ NarwhalsTableManager,
+)
+from marimo._plugins.ui._impl.tables.table_manager import TableManager
+from tests.mocks import snapshotter
+
+HAS_DEPS = DependencyManager.polars.has()
+
+snapshot = snapshotter(__file__)
+
+
+def assert_frame_equal(a: Any, b: Any) -> None:
+ return a.to_dict() == b.to_dict()
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+class TestNarwhalsTableManagerFactory(unittest.TestCase):
+ def get_complex_data(self) -> TableManager[Any]:
+ import polars as pl
+
+ complex_data = pl.DataFrame(
+ {
+ "strings": ["a", "b", "c"],
+ "bool": [True, False, True],
+ "int": [1, 2, 3],
+ "float": [1.0, 2.0, 3.0],
+ "datetime": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "struct": [
+ {"a": 1, "b": 2},
+ {"a": 3, "b": 4},
+ {"a": 5, "b": 6},
+ ],
+ "list": [[1, 2], [3, 4], [5, 6]],
+ "array": [[1, 2, 3], [4], []],
+ "nulls": [None, "data", None],
+ "categorical": pl.Series(["cat", "dog", "mouse"]).cast(
+ pl.Categorical
+ ),
+ # raises:
+ # pyo3_runtime.PanicException:
+ # not yet implemented: Writing Time64(Nanosecond) to JSON
+ # "time": [
+ # datetime.time(12, 30),
+ # datetime.time(13, 45),
+ # datetime.time(14, 15),
+ # ],
+ "duration": [
+ datetime.timedelta(days=1),
+ datetime.timedelta(days=2),
+ datetime.timedelta(days=3),
+ ],
+ "mixed_list": [
+ [1, "two"],
+ [3.0, False],
+ [None, datetime.datetime(2021, 1, 1)],
+ ],
+ },
+ strict=False,
+ )
+
+ return NarwhalsTableManager.from_dataframe(complex_data)
+
+ def setUp(self) -> None:
+ import polars as pl
+
+ self.data = pl.DataFrame(
+ { # type: ignore
+ # Integer
+ "A": [1, 2, 3],
+ # String
+ "B": ["aaa", "b", "c"],
+ # Float
+ "C": [1.0, 2.0, 3.0],
+ # Boolean
+ "D": [True, False, True],
+ # DateTime
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
+ self.manager = NarwhalsTableManager.from_dataframe(self.data)
+
+ def test_to_csv(self) -> None:
+ assert isinstance(self.manager.to_csv(), bytes)
+ import polars as pl
+
+ complex_data = self.get_complex_data()
+ with pytest.raises(pl.exceptions.ComputeError):
+ # Polars doesn't support writing nested lists to csv
+ complex_data.to_csv()
+
+ def test_to_csv_array(self) -> None:
+ import numpy as np
+ import polars as pl
+
+ df = pl.DataFrame(
+ {"a": [np.arange(5) for _ in range(10)]},
+ schema={"a": pl.Array(pl.Int64, 5)},
+ )
+ manager = NarwhalsTableManager.from_dataframe(df)
+ with pytest.raises(pl.exceptions.ComputeError):
+ # Polars doesn't support writing nested lists to csv
+ manager.to_csv()
+
+ def test_to_json(self) -> None:
+ assert isinstance(self.manager.to_json(), bytes)
+ import polars as pl
+
+ complex_data = self.get_complex_data()
+ with pytest.raises(pl.exceptions.ComputeError):
+ # Polars doesn't support writing nested lists to json
+ complex_data.to_json()
+
+ def test_complex_data_field_types(self) -> None:
+ complex_data = self.get_complex_data()
+ field_types = complex_data.get_field_types()
+ snapshot("narwhals.field_types.json", json.dumps(field_types))
+
+ def test_select_rows(self) -> None:
+ indices = [0, 2]
+ selected_manager = self.manager.select_rows(indices)
+ expected_data = self.data[indices]
+ assert_frame_equal(selected_manager.data, expected_data)
+
+ def test_select_rows_empty(self) -> None:
+ selected_manager = self.manager.select_rows([])
+ assert selected_manager.data.shape == (0, 5)
+ assert selected_manager.data.columns == ["A", "B", "C", "D", "E"]
+
+ def test_select_columns(self) -> None:
+ columns = ["A"]
+ selected_manager = self.manager.select_columns(columns)
+ expected_data = self.data.select(columns)
+ assert_frame_equal(selected_manager.data, expected_data)
+
+ def test_get_row_headers(self) -> None:
+ expected_headers = []
+ assert self.manager.get_row_headers() == expected_headers
+
+ def test_is_type(self) -> None:
+ assert self.manager.is_type(self.data)
+ assert not self.manager.is_type("not a dataframe")
+
+ def test_get_field_types(self) -> None:
+ import polars as pl
+
+ expected_field_types = {
+ "A": ("integer", "Int64"),
+ "B": ("string", "String"),
+ "C": ("number", "Float64"),
+ "D": ("boolean", "Boolean"),
+ "E": ("date", "Datetime(time_unit='us', time_zone=None)"),
+ }
+ assert self.manager.get_field_types() == expected_field_types
+
+ complex_data = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [1 + 2j, 3 + 4j, 5 + 6j],
+ "F": [None, None, None],
+ "G": [set([1, 2]), set([3, 4]), set([5, 6])],
+ "H": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "I": [
+ "1 days",
+ "2 days",
+ "3 days",
+ ],
+ "J": [
+ "0-5",
+ "5-10",
+ "10-15",
+ ],
+ }
+ )
+ expected_field_types = {
+ "A": ("integer", "Int64"),
+ "B": ("string", "String"),
+ "C": ("number", "Float64"),
+ "D": ("boolean", "Boolean"),
+ "E": ("unknown", "Object"),
+ "F": ("unknown", "Unknown"),
+ "G": ("unknown", "Object"),
+ "H": ("date", "Datetime(time_unit='us', time_zone=None)"),
+ "I": ("string", "String"),
+ "J": ("string", "String"),
+ }
+ assert (
+ NarwhalsTableManager.from_dataframe(complex_data).get_field_types()
+ == expected_field_types
+ )
+
+ def test_limit(self) -> None:
+ limited_manager = self.manager.take(1, 0)
+ expected_data = self.data.head(1)
+ assert_frame_equal(limited_manager.data, expected_data)
+
+ def test_take_out_of_bounds(self) -> None:
+ # Too large of page
+ assert len(self.manager.take(10, 0).data) == 3
+ assert len(self.data) == 3
+
+ # Too large of page and offset
+ assert self.manager.take(10, 10).data.is_empty()
+
+ def test_summary_integer(self) -> None:
+ column = "A"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ min=1,
+ max=3,
+ mean=2.0,
+ # median=2.0,
+ std=1.0,
+ p5=1.0,
+ p25=2.0,
+ p75=3.0,
+ p95=3.0,
+ )
+
+ def test_summary_string(self) -> None:
+ column = "B"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ )
+
+ def test_summary_number(self) -> None:
+ column = "C"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=1.0,
+ max=3.0,
+ mean=2.0,
+ # median=2.0,
+ std=1.0,
+ p5=1.0,
+ p25=2.0,
+ p75=3.0,
+ p95=3.0,
+ )
+
+ def test_summary_boolean(self) -> None:
+ column = "D"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ true=2,
+ false=1,
+ )
+
+ def test_summary_datetime(self) -> None:
+ column = "E"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=datetime.datetime(2021, 1, 1, 0, 0),
+ max=datetime.datetime(2021, 1, 3, 0, 0),
+ mean=datetime.datetime(2021, 1, 2, 0, 0),
+ # median=datetime.datetime(2021, 1, 2, 0, 0),
+ )
+
+ def test_summary_date(self) -> None:
+ import polars as pl
+
+ data = pl.DataFrame(
+ {
+ "A": [datetime.date(2021, 1, 1), datetime.date(2021, 1, 2)],
+ }
+ )
+ manager = NarwhalsTableManager.from_dataframe(data)
+ summary = manager.get_summary("A")
+ assert summary == ColumnSummary(
+ total=2,
+ nulls=0,
+ min=datetime.date(2021, 1, 1),
+ max=datetime.date(2021, 1, 2),
+ mean=datetime.datetime(2021, 1, 1, 12, 0),
+ # median=datetime.datetime(2021, 1, 1, 12, 0),
+ )
+
+ def test_sort_values(self) -> None:
+ sorted_df = self.manager.sort_values("A", descending=True).data
+ expected_df = self.data.sort("A", descending=True)
+ assert_frame_equal(sorted_df, expected_df)
+
+ def test_get_unique_column_values(self) -> None:
+ column = "A"
+ unique_values = self.manager.get_unique_column_values(column)
+ assert unique_values == [1, 2, 3]
+
+ def test_search(self) -> None:
+ import polars as pl
+
+ df = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["foo", "bar", "baz"],
+ "C": [True, False, True],
+ "D": [["zz", "yyy"], [], []],
+ "E": [1.1, 2.2, 3.3],
+ }
+ )
+ manager = NarwhalsTableManager.from_dataframe(df)
+ # Exact match
+ assert manager.search("foo").get_num_rows() == 1
+ # Contains
+ assert manager.search("a").get_num_rows() == 2
+ # Case insensitive / boolean
+ assert manager.search("true").get_num_rows() == 2
+ # Overmatch
+ assert manager.search("food").get_num_rows() == 0
+ # Int (exact match)
+ assert manager.search("1").get_num_rows() == 1
+ # Float (exact match)
+ assert manager.search("1.1").get_num_rows() == 1
+ # List (exact match)
+ # TODO: Unsupported by narwhals
+ assert manager.search("yyy").get_num_rows() == 0
+ assert manager.search("y").get_num_rows() == 0
+
+ def test_apply_formatting_does_not_modify_original_data(self) -> None:
+ original_data = self.data.clone()
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+ self.manager.apply_formatting(format_mapping)
+ assert_frame_equal(self.manager.data, original_data)
+
+ def test_apply_formatting(self) -> None:
+ import polars as pl
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["AAA", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_empty_dataframe(self) -> None:
+ import polars as pl
+
+ empty_data = pl.DataFrame(
+ {"A": []}
+ ) # Create an empty DataFrame with a column
+ manager = NarwhalsTableManager.from_dataframe(empty_data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ assert_frame_equal(formatted_data, empty_data)
+
+ def test_apply_formatting_partial(self) -> None:
+ import polars as pl
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_empty(self) -> None:
+ format_mapping: FormatMapping = {}
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert_frame_equal(formatted_data, self.data)
+
+ def test_apply_formatting_invalid_column(self) -> None:
+ format_mapping: FormatMapping = {
+ "Z": lambda x: x * 2,
+ }
+
+ formatted_data = self.manager.apply_formatting(format_mapping)
+ assert_frame_equal(formatted_data, self.data)
+
+ def test_apply_formatting_with_nan(self) -> None:
+ import polars as pl
+
+ data_with_nan = self.data.clone()
+ data_with_nan = data_with_nan.with_columns(
+ pl.when(pl.col("A").is_not_null())
+ .then(pl.col("A"))
+ .otherwise(None)
+ .alias("A")
+ )
+ manager_with_nan = NarwhalsTableManager.from_dataframe(data_with_nan)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2 if x is not None else x,
+ }
+
+ formatted_data = manager_with_nan.apply_formatting(format_mapping)
+ expected_data = data_with_nan.clone()
+ expected_data = expected_data.with_columns(
+ pl.when(pl.col("A").is_not_null())
+ .then(pl.col("A") * 2)
+ .otherwise(None)
+ .alias("A")
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_multi_index(self) -> None:
+ import polars as pl
+
+ data = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ }
+ ).with_row_index()
+ data = data.with_columns(pl.col("index").cast(pl.Utf8))
+
+ manager = NarwhalsTableManager.from_dataframe(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "index": ["0", "1", "2"],
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_categorical_data(self) -> None:
+ import polars as pl
+
+ data = pl.DataFrame(
+ {
+ "A": pl.Series(["a", "b", "a"]).cast(pl.Categorical),
+ "B": [1, 2, 3],
+ }
+ )
+ manager = NarwhalsTableManager.from_dataframe(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x.upper(),
+ "B": lambda x: x * 2,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": pl.Series(["A", "B", "A"]),
+ "B": [2, 4, 6],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_datetime_index(self) -> None:
+ import polars as pl
+
+ data = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ }
+ ).with_columns(
+ pl.date_range(
+ start=datetime.datetime(2021, 1, 1),
+ end=datetime.datetime(2021, 1, 3),
+ interval="1d",
+ ).alias("index")
+ )
+ data = data.with_columns(pl.col("index").cast(pl.Utf8))
+
+ manager = NarwhalsTableManager.from_dataframe(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "index": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_apply_formatting_with_complex_data(self) -> None:
+ import polars as pl
+
+ data = pl.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": ["a", "b", "c"],
+ "C": [1.0, 2.0, 3.0],
+ "D": [True, False, True],
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "F": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ "G": [1 + 2j, 3 + 4j, 5 + 6j],
+ }
+ )
+ manager = NarwhalsTableManager.from_dataframe(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ "B": lambda x: x.upper(),
+ "C": lambda x: f"{x:.2f}",
+ "D": lambda x: not x,
+ "E": lambda x: x.strftime("%Y-%m-%d"),
+ "G": abs,
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping)
+ expected_data = pl.DataFrame(
+ {
+ "A": [2, 4, 6],
+ "B": ["A", "B", "C"],
+ "C": ["1.00", "2.00", "3.00"],
+ "D": [False, True, False],
+ "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
+ "F": [
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ ], # No formatting applied
+ "G": [2.23606797749979, 5.0, 7.810249675906654],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
+ def test_empty_dataframe(self) -> None:
+ import polars as pl
+
+ empty_df = pl.DataFrame()
+ empty_manager = NarwhalsTableManager.from_dataframe(empty_df)
+ assert empty_manager.get_num_rows() == 0
+ assert empty_manager.get_num_columns() == 0
+ assert empty_manager.get_column_names() == []
+ assert empty_manager.get_field_types() == {}
+
+ def test_dataframe_with_all_null_column(self) -> None:
+ import polars as pl
+
+ df = pl.DataFrame({"A": [1, 2, 3], "B": [None, None, None]})
+ manager = NarwhalsTableManager.from_dataframe(df)
+ summary = manager.get_summary("B")
+ assert summary.nulls == 3
+ assert summary.total == 3
+
+ def test_dataframe_with_mixed_types(self) -> None:
+ import polars as pl
+
+ df = pl.DataFrame({"A": [1, "two", 3.0, True]}, strict=False)
+ manager = NarwhalsTableManager.from_dataframe(df)
+ field_types = manager.get_field_types()
+ assert field_types["A"] == ("string", "String")
+
+ def test_search_with_regex(self) -> None:
+ import polars as pl
+
+ df = pl.DataFrame({"A": ["apple", "banana", "cherry"]})
+ manager = NarwhalsTableManager.from_dataframe(df)
+ result = manager.search("^[ab]")
+ assert result.get_num_rows() == 2
+
+ def test_sort_values_with_nulls(self) -> None:
+ import polars as pl
+
+ df = pl.DataFrame({"A": [3, 1, None, 2]})
+ manager = NarwhalsTableManager.from_dataframe(df)
+ sorted_manager = manager.sort_values("A", descending=True)
+ assert sorted_manager.data["A"].to_list() == [None, 3, 2, 1]
diff --git a/tests/_plugins/ui/_impl/tables/test_pyarrow.py b/tests/_plugins/ui/_impl/tables/test_pyarrow.py
deleted file mode 100644
index 47427608cd..0000000000
--- a/tests/_plugins/ui/_impl/tables/test_pyarrow.py
+++ /dev/null
@@ -1,548 +0,0 @@
-from __future__ import annotations
-
-import datetime
-import unittest
-
-import pytest
-
-from marimo._data.models import ColumnSummary
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._plugins.ui._impl.tables.pyarrow_table import (
- PyArrowTableManagerFactory,
-)
-
-HAS_DEPS_TABLE = DependencyManager.pyarrow.has()
-HAS_DEPS_RECORD_BATCH = (
- DependencyManager.pandas.has() and DependencyManager.pyarrow.has()
-)
-
-
- not HAS_DEPS_TABLE, reason="optional dependencies not installed"
-)
-class TestPyArrowTableManagerFactory(unittest.TestCase):
- def setUp(self) -> None:
- import pyarrow as pa
-
- self.factory = PyArrowTableManagerFactory()
- self.data = pa.table(
- { # type: ignore
- # Integer
- "A": [1, 2, 3],
- # String
- "B": ["aaa", "b", "c"],
- # Float
- "C": [1.0, 2.0, 3.0],
- # Boolean
- "D": [True, False, True],
- # DateTime
- "E": [
- datetime.datetime(2021, 1, 1),
- datetime.datetime(2021, 1, 2),
- datetime.datetime(2021, 1, 3),
- ],
- }
- )
- self.manager = self.factory.create()(self.data)
-
- def test_package_name(self) -> None:
- assert self.factory.package_name() == "pyarrow"
-
- def test_to_csv(self) -> None:
- assert isinstance(self.manager.to_csv(), bytes)
-
- def test_to_json(self) -> None:
- assert isinstance(self.manager.to_json(), bytes)
-
- def test_select_rows(self) -> None:
- indices = [0, 2]
- selected_manager = self.manager.select_rows(indices)
- expected_data = self.data.take(indices)
- assert selected_manager.data == expected_data
-
- def test_select_rows_empty(self) -> None:
- selected_manager = self.manager.select_rows([])
- assert selected_manager.data.num_rows == 0
-
- def test_select_columns(self) -> None:
- columns = ["A"]
- selected_manager = self.manager.select_columns(columns)
- expected_data = self.data.select(columns)
- assert selected_manager.data == expected_data
-
- def test_get_row_headers(self) -> None:
- expected_headers = []
- assert self.manager.get_row_headers() == expected_headers
-
- def test_is_type(self) -> None:
- assert self.manager.is_type(self.data)
- assert not self.manager.is_type("not a dataframe")
-
- def test_get_field_types(self) -> None:
- import pyarrow as pa
-
- expected_field_types = {
- "A": ("integer", "int64"),
- "B": ("string", "string"),
- "C": ("number", "double"),
- "D": ("boolean", "bool"),
- "E": ("date", "timestamp[us]"),
- }
- assert self.manager.get_field_types() == expected_field_types
-
- complex_data = pa.table(
- {
- "A": [1, 2, 3],
- "B": ["aaa", "b", "c"],
- "C": [1.0, 2.0, 3.0],
- "D": [True, False, True],
- "E": [None, None, None],
- } # type: ignore
- )
- expected_field_types = {
- "A": ("integer", "int64"),
- "B": ("string", "string"),
- "C": ("number", "double"),
- "D": ("boolean", "bool"),
- "E": ("unknown", "null"),
- }
- assert (
- self.factory.create()(complex_data).get_field_types()
- == expected_field_types
- )
-
- def test_limit(self) -> None:
- limited_manager = self.manager.take(1, 0)
- expected_data = self.data.take([0])
- assert limited_manager.data == expected_data
-
- def test_take_out_of_bounds(self) -> None:
- # Too large of page
- assert self.manager.take(10, 0).data == self.data
-
- # Too large of page and offset
- assert len(self.manager.take(10, 10).data) == 0
-
- def test_limit_more_than_num_rows(self) -> None:
- limited_manager = self.manager.take(500, 0)
- assert limited_manager.data == self.data
-
- def test_summary_integer(self) -> None:
- column = "A"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- unique=3,
- min=1,
- max=3,
- mean=2.0,
- )
-
- def test_summary_string(self) -> None:
- column = "B"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- unique=3,
- )
-
- def test_summary_number(self) -> None:
- column = "C"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- min=1.0,
- max=3.0,
- mean=2.0,
- )
-
- def test_summary_boolean(self) -> None:
- column = "D"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- true=2,
- false=1,
- )
-
- def test_summary_date(self) -> None:
- column = "E"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- min=datetime.datetime(2021, 1, 1, 0, 0),
- max=datetime.datetime(2021, 1, 3, 0, 0),
- )
-
- def test_sort_values(self) -> None:
- sorted_df = self.manager.sort_values("A", descending=True).data
- expected_df = self.data.sort_by([("A", "descending")])
- assert sorted_df.equals(expected_df)
-
- def test_get_unique_column_values(self) -> None:
- column = "B"
- unique_values = self.manager.get_unique_column_values(column)
- assert unique_values == ["aaa", "b", "c"]
-
- def test_search(self) -> None:
- manager = self.factory.create()(self.data)
- assert manager.search("aaa").get_num_rows() == 1
- assert manager.search("true").get_num_rows() == 2
- assert manager.search("baz").get_num_rows() == 0
-
- def test_apply_formatting(self) -> None:
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- "B": lambda x: x.upper(),
- "C": lambda x: f"{x:.2f}",
- "D": lambda x: not x,
- "E": lambda x: x.strftime("%Y-%m-%d"),
- }
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- expected_data = pa.table(
- {
- "A": [2, 4, 6],
- "B": ["AAA", "B", "C"],
- "C": ["1.00", "2.00", "3.00"],
- "D": [False, True, False],
- "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
- }
- )
- assert formatted_data.equals(expected_data)
-
- def test_apply_formatting_with_empty_table(self) -> None:
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- empty_data = pa.table({})
- manager = self.factory.create()(empty_data)
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- }
-
- formatted_data = manager.apply_formatting(format_mapping)
- assert formatted_data.equals(empty_data)
-
- def test_apply_formatting_partial(self) -> None:
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- }
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- expected_data = pa.table(
- {
- "A": [2, 4, 6],
- "B": ["aaa", "b", "c"],
- "C": [1.0, 2.0, 3.0],
- "D": [True, False, True],
- "E": [
- datetime.datetime(2021, 1, 1),
- datetime.datetime(2021, 1, 2),
- datetime.datetime(2021, 1, 3),
- ],
- }
- )
- assert formatted_data.equals(expected_data)
-
- def test_apply_formatting_empty(self) -> None:
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {}
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- assert formatted_data.equals(self.data)
-
- def test_apply_formatting_invalid_column(self) -> None:
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "Z": lambda x: x * 2,
- }
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- assert formatted_data.equals(self.data)
-
-
- not HAS_DEPS_RECORD_BATCH, reason="optional dependencies not installed"
-)
-class TestPyArrowRecordBatchManagerFactory(unittest.TestCase):
- def setUp(self) -> None:
- import pandas as pd
- import pyarrow as pa
-
- self.factory = PyArrowTableManagerFactory()
- self.data = pa.RecordBatch.from_pandas(
- pd.DataFrame(
- {
- "A": [1, 2, 3],
- "B": ["aaa", "b", "c"],
- "C": [1.0, 2.0, 3.0],
- "D": [True, False, True],
- "E": [
- datetime.datetime(2021, 1, 1),
- datetime.datetime(2021, 1, 2),
- datetime.datetime(2021, 1, 3),
- ],
- }
- )
- )
- self.manager = self.factory.create()(self.data)
-
- def test_package_name(self) -> None:
- assert self.factory.package_name() == "pyarrow"
-
- def test_to_csv(self) -> None:
- assert isinstance(self.manager.to_csv(), bytes)
-
- def test_to_json(self) -> None:
- assert isinstance(self.manager.to_json(), bytes)
-
- def test_select_rows(self) -> None:
- indices = [0, 2]
- selected_manager = self.manager.select_rows(indices)
- expected_data = self.data.take(indices)
- assert selected_manager.data == expected_data
-
- def test_select_rows_empty(self) -> None:
- selected_manager = self.manager.select_rows([])
- assert selected_manager.data.num_rows == 0
-
- def test_select_columns(self) -> None:
- columns = ["A"]
- selected_manager = self.manager.select_columns(columns)
- expected_data = self.data.select(columns)
- assert selected_manager.data == expected_data
-
- def test_get_row_headers(self) -> None:
- expected_headers = []
- assert self.manager.get_row_headers() == expected_headers
-
- def test_is_type(self) -> None:
- assert self.manager.is_type(self.data)
- assert not self.manager.is_type("not a dataframe")
-
- def test_get_field_types(self) -> None:
- import pandas as pd
- import pyarrow as pa
-
- expected_field_types = {
- "A": ("integer", "int64"),
- "B": ("string", "string"),
- "C": ("number", "double"),
- "D": ("boolean", "bool"),
- "E": ("date", "timestamp[ns]"),
- }
- assert self.manager.get_field_types() == expected_field_types
-
- complex_data = pa.RecordBatch.from_pandas(
- pd.DataFrame(
- {
- "A": [1, 2, 3],
- "B": ["aaa", "b", "c"],
- "C": [1.0, 2.0, 3.0],
- "D": [True, False, True],
- "E": [None, None, None],
- }
- )
- )
- expected_field_types = {
- "A": ("integer", "int64"),
- "B": ("string", "string"),
- "C": ("number", "double"),
- "D": ("boolean", "bool"),
- "E": ("unknown", "null"),
- }
- assert (
- self.factory.create()(complex_data).get_field_types()
- == expected_field_types
- )
-
- def test_limit(self) -> None:
- limited_manager = self.manager.take(1, 0)
- expected_data = self.data.slice(0, 1)
- assert limited_manager.data == expected_data
-
- def test_take_out_of_bounds(self) -> None:
- # Too large of page
- assert self.manager.take(10, 0).data == self.data
-
- # Too large of page and offset
- assert len(self.manager.take(10, 10).data) == 0
-
- def test_limit_more_than_num_rows(self) -> None:
- limited_manager = self.manager.take(500, 0)
- assert limited_manager.data == self.data
-
- def test_summary_integer(self) -> None:
- column = "A"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- unique=3,
- min=1,
- max=3,
- mean=2.0,
- )
-
- def test_summary_string(self) -> None:
- column = "B"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- unique=3,
- )
-
- def test_summary_number(self) -> None:
- column = "C"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- min=1.0,
- max=3.0,
- mean=2.0,
- )
-
- def test_summary_boolean(self) -> None:
- column = "D"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- true=2,
- false=1,
- )
-
- def test_summary_date(self) -> None:
- column = "E"
- summary = self.manager.get_summary(column)
- assert summary == ColumnSummary(
- total=3,
- nulls=0,
- min=datetime.datetime(2021, 1, 1, 0, 0),
- max=datetime.datetime(2021, 1, 3, 0, 0),
- )
-
- def test_sort_values(self) -> None:
- sorted_df = self.manager.sort_values("A", descending=True).data
- expected_df = self.data.sort_by([("A", "descending")])
- assert sorted_df.equals(expected_df)
-
- def test_get_unique_column_values(self) -> None:
- column = "B"
- unique_values = self.manager.get_unique_column_values(column)
- assert unique_values == ["aaa", "b", "c"]
-
- def test_search(self) -> None:
- manager = self.factory.create()(self.data)
- assert manager.search("aaa").get_num_rows() == 1
- assert manager.search("true").get_num_rows() == 2
- assert manager.search("baz").get_num_rows() == 0
-
- def test_apply_formatting(self) -> None:
- import pandas as pd
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- "B": lambda x: x.upper(),
- "C": lambda x: f"{x:.2f}",
- "D": lambda x: not x,
- "E": lambda x: x.strftime("%Y-%m-%d"),
- }
- formatted_data = self.manager.apply_formatting(format_mapping)
- expected_data = pa.RecordBatch.from_pandas(
- pd.DataFrame(
- {
- "A": [2, 4, 6],
- "B": ["AAA", "B", "C"],
- "C": ["1.00", "2.00", "3.00"],
- "D": [False, True, False],
- "E": ["2021-01-01", "2021-01-02", "2021-01-03"],
- }
- )
- )
- assert formatted_data.equals(expected_data)
-
- def test_apply_formatting_with_empty_table(self) -> None:
- import pandas as pd
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- empty_data = pa.RecordBatch.from_pandas(pd.DataFrame({}))
- manager = self.factory.create()(empty_data)
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- }
-
- formatted_data = manager.apply_formatting(format_mapping)
- assert formatted_data.equals(empty_data)
-
- def test_apply_formatting_partial(self) -> None:
- import pandas as pd
- import pyarrow as pa
-
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "A": lambda x: x * 2,
- }
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- expected_data = pa.RecordBatch.from_pandas(
- pd.DataFrame(
- {
- "A": [2, 4, 6],
- "B": ["aaa", "b", "c"],
- "C": [1.0, 2.0, 3.0],
- "D": [True, False, True],
- "E": [
- datetime.datetime(2021, 1, 1),
- datetime.datetime(2021, 1, 2),
- datetime.datetime(2021, 1, 3),
- ],
- }
- )
- )
- assert formatted_data.equals(expected_data)
-
- def test_apply_formatting_empty(self) -> None:
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {}
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- assert formatted_data.equals(self.data)
-
- def test_apply_formatting_invalid_column(self) -> None:
- from marimo._plugins.ui._impl.tables.format import FormatMapping
-
- format_mapping: FormatMapping = {
- "Z": lambda x: x * 2,
- }
-
- formatted_data = self.manager.apply_formatting(format_mapping)
- assert formatted_data.equals(self.data)
diff --git a/tests/_plugins/ui/_impl/tables/test_table_utils.py b/tests/_plugins/ui/_impl/tables/test_table_utils.py
index d558bd5410..4b39d172e5 100644
--- a/tests/_plugins/ui/_impl/tables/test_table_utils.py
+++ b/tests/_plugins/ui/_impl/tables/test_table_utils.py
@@ -1,49 +1,10 @@
from __future__ import annotations
-import pytest
-
-from marimo._plugins.ui._impl.tables.df_protocol_table import (
- DataFrameProtocolTableManager,
-)
from marimo._plugins.ui._impl.tables.format import (
format_column,
format_row,
format_value,
)
-from marimo._plugins.ui._impl.tables.types import is_dataframe_like
-
-
-class Fake:
- def __getattr__(self, _):
- return ...
-
-
-class FakeReturningCallable:
- def __getattr__(self, _):
- return lambda: ...
-
-
-class Real:
- def __dataframe__(self):
- return ...
-
-
-def test_is_dataframe_like():
- # Primitives
- assert is_dataframe_like(1) is False
- assert is_dataframe_like("1") is False
- assert is_dataframe_like([]) is False
- assert is_dataframe_like({}) is False
- assert is_dataframe_like(()) is False
-
- assert is_dataframe_like(Fake()) is False
- assert is_dataframe_like(FakeReturningCallable()) is False
- assert is_dataframe_like(Real()) is True
-
-
-def test_df_protocol_manager_throws():
- with pytest.raises(ValueError):
- DataFrameProtocolTableManager(Real())
def test_format_value():
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index a0f0d2a95a..cf4d232672 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import datetime
import json
import sys
+from typing import TYPE_CHECKING
from unittest.mock import Mock
import narwhals.stable.v1 as nw
@@ -15,6 +16,7 @@ from marimo._plugins.ui._impl.altair_chart import (
ChartDataType,
ChartSelection,
_filter_dataframe,
+ _has_binning,
_has_geoshape,
_parse_spec,
)
@@ -23,6 +25,9 @@ from tests._data.mocks import create_dataframes
from tests.conftest import ExecReqProvider
from tests.mocks import snapshotter
+if TYPE_CHECKING:
+ from narwhals.typing import IntoDataFrame
+
snapshot = snapshotter(__file__)
HAS_DEPS = (
@@ -72,8 +77,8 @@ class TestAltairChart:
# Filter the DataFrame with the point selection
assert len(_filter_dataframe(df, point_selection)) == 2
first, second = _filter_dataframe(df, point_selection)["field"]
- assert first == "value2"
- assert second == "value3"
+ assert str(first) == "value2"
+ assert str(second) == "value3"
# Define an interval selection
interval_selection: ChartSelection = {
@@ -140,8 +145,8 @@ class TestAltairChart:
# Filter the DataFrame with the interval selection
assert len(_filter_dataframe(df, interval_selection)) == 2
first, second = _filter_dataframe(df, interval_selection)["field"]
- assert first == "value1"
- assert second == "value2"
+ assert str(first) == "value1"
+ assert str(second) == "value2"
# Define an interval selection with a datetime column
interval_selection: ChartSelection = {
@@ -156,8 +161,8 @@ class TestAltairChart:
# Filter the DataFrame with the interval selection
assert len(_filter_dataframe(df, interval_selection)) == 2
first, second = _filter_dataframe(df, interval_selection)["field"]
- assert first == "value1"
- assert second == "value2"
+ assert str(first) == "value1"
+ assert str(second) == "value2"
@staticmethod
async def test_altair_settings_when_set(
@@ -415,3 +420,112 @@ def test_no_selection_polars() -> None:
assert isinstance(selected_value, pl.DataFrame)
selected_value = chart._convert_value(None)
assert isinstance(selected_value, pl.DataFrame)
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"x": [1, 2, 3], "y1": [4, 5, 6], "y2": [7, 8, 9]}, exclude=["ibis"]
+ ),
+)
+def test_layered_chart(df: IntoDataFrame):
+ import altair as alt
+
+ base = alt.Chart(df).encode(x="x")
+ chart1 = base.mark_line().encode(y="y1")
+ chart2 = base.mark_line().encode(y="y2")
+ layered = alt.layer(chart1, chart2)
+
+ marimo_chart = altair_chart.altair_chart(layered)
+ assert isinstance(marimo_chart._chart, alt.LayerChart)
+ assert marimo_chart.dataframe is not None
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes({"values": list(range(100))}),
+)
+def test_chart_with_binning(df: IntoDataFrame):
+ import altair as alt
+
+ chart = (
+ alt.Chart(df)
+ .mark_bar()
+ .encode(x=alt.X("values", bin=True), y="count()")
+ )
+
+ marimo_chart = altair_chart.altair_chart(chart)
+ assert _has_binning(marimo_chart._spec)
+ # Test that selection is disabled for binned charts
+ assert marimo_chart._component_args["chart-selection"] is False
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {
+ "x": [1, 2, 3, 4],
+ "y": [1, 2, 3, 4],
+ "category": ["A", "A", "B", "B"],
+ },
+ exclude=["ibis", "pyarrow"],
+ ),
+)
+def test_apply_selection(df: IntoDataFrame):
+ import altair as alt
+
+ chart = alt.Chart(df).mark_point().encode(x="x", y="y", color="category")
+
+ marimo_chart = altair_chart.altair_chart(chart)
+ marimo_chart._chart_selection = {"signal_channel": {"category": ["A"]}}
+
+ filtered_data = marimo_chart.apply_selection(df)
+ assert len(filtered_data) == 2
+ assert all(filtered_data["category"] == "A")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_chart_with_url_data():
+ import altair as alt
+ import polars as pl
+
+ url = "https://vega.github.io/vega-datasets/data/cars.json"
+ chart = (
+ alt.Chart(url)
+ .mark_point()
+ .encode(x="Horsepower:Q", y="Miles_per_Gallon:Q")
+ )
+
+ marimo_chart = altair_chart.altair_chart(chart)
+ assert isinstance(marimo_chart.dataframe, pl.DataFrame)
+ assert len(marimo_chart.dataframe) > 0
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes({"x": [1, 2, 3], "y": [4, 5, 6]}),
+)
+def test_chart_operations(df: IntoDataFrame):
+ import altair as alt
+
+ chart1 = alt.Chart(df).mark_point().encode(x="x", y="y")
+ chart2 = alt.Chart(df).mark_line().encode(x="x", y="y")
+
+ marimo_chart1 = altair_chart.altair_chart(chart1)
+ marimo_chart2 = altair_chart.altair_chart(chart2)
+
+ combined_chart = marimo_chart1 + marimo_chart2
+ assert isinstance(combined_chart, altair_chart.altair_chart)
+ assert isinstance(combined_chart._chart, alt.LayerChart)
+
+ concat_chart = marimo_chart1 | marimo_chart2
+ assert isinstance(concat_chart, altair_chart.altair_chart)
+ assert isinstance(concat_chart._chart, alt.HConcatChart)
+
+ facet_chart = marimo_chart1 & marimo_chart2
+ assert isinstance(facet_chart, altair_chart.altair_chart)
+ assert isinstance(facet_chart._chart, alt.VConcatChart)
diff --git a/tests/_utils/test_narwhals_utils.py b/tests/_utils/test_narwhals_utils.py
index ac535d4e88..9a20a6866b 100644
--- a/tests/_utils/test_narwhals_utils.py
+++ b/tests/_utils/test_narwhals_utils.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import narwhals.stable.v1 as nw
import pytest
@@ -28,9 +28,9 @@ if TYPE_CHECKING:
)
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
def test_empty_df(df: IntoDataFrame) -> None:
- empty = empty_df(df)
- assert empty.shape == (0, 2)
- assert list(empty.columns) == ["a", "b"]
+ empty: Any = empty_df(df)
+ assert len(empty) == 0
+ assert len(empty.columns) == 2
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")