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.

feat: support ibis and the dataframe protocol (#1522)

Myles Scolnick861d07636e93
diff --git a/frontend/src/core/datasets/state.ts b/frontend/src/core/datasets/state.ts
index 32fecd776c..51e6cd9b72 100644
--- a/frontend/src/core/datasets/state.ts
+++ b/frontend/src/core/datasets/state.ts
@@ -34,9 +34,12 @@ const {
seen.add(key);
return true;
});
+ const sortedTables = dedupedTables.sort((a, b) => {
+ return a.name.localeCompare(b.name);
+ });
return {
...state,
- tables: dedupedTables,
+ tables: sortedTables,
};
},
filterDatasetsFromVariables: (state, variableNames: VariableName[]) => {
diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.py
index 1a825a7ea4..05b25e110e 100644
--- a/marimo/_data/get_datasets.py
+++ b/marimo/_data/get_datasets.py
@@ -3,9 +3,12 @@ from __future__ import annotations
from typing import List, Optional
+from marimo import _loggers
from marimo._data.models import DataTable, DataTableColumn
from marimo._plugins.ui._impl.tables.utils import get_table_manager_or_none
+LOGGER = _loggers.marimo_logger()
+
def get_datasets_from_variables(
variables: List[tuple[str, object]],
@@ -22,16 +25,25 @@ def get_datasets_from_variables(
def get_data_table(value: object, variable_name: str) -> Optional[DataTable]:
table = get_table_manager_or_none(value)
if table is not None:
- return DataTable(
- name=variable_name,
- variable_name=variable_name,
- num_rows=table.get_num_rows(),
- num_columns=table.get_num_columns(),
- source=f"Local ({table.type})",
- columns=[
+ try:
+ columns = [
DataTableColumn(name=column_name, type=column_type)
for column_name, column_type in table.get_field_types().items()
- ],
- )
+ ]
+ return DataTable(
+ name=variable_name,
+ variable_name=variable_name,
+ num_rows=table.get_num_rows(),
+ num_columns=table.get_num_columns(),
+ source=f"Local ({table.type})",
+ columns=columns,
+ )
+ except Exception as e:
+ LOGGER.error(
+ "Failed to get table data for variable %s",
+ variable_name,
+ exc_info=e,
+ )
+ return None
return None
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index c9b472ef9f..e912030a19 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -97,6 +97,21 @@ class DependencyManager:
+ "You can install it with 'pip install plotly'"
) from None
+ @staticmethod
+ def require_pyarrow(why: str) -> None:
+ """
+ Raise an ModuleNotFoundError if pyarrow is not installed.
+
+ Args:
+ why: A string of the form "for <reason>" that will be appended
+
+ """
+ if not DependencyManager.has_pyarrow():
+ raise ModuleNotFoundError(
+ f"pyarrow is required {why}. "
+ + "You can install it with 'pip install pyarrow'"
+ ) from None
+
@staticmethod
def has(pkg: str) -> bool:
"""Return True if any lib is installed."""
diff --git a/marimo/_plugins/ui/_impl/data_explorer.py b/marimo/_plugins/ui/_impl/data_explorer.py
index bd5e382d24..14ce2e5860 100644
--- a/marimo/_plugins/ui/_impl/data_explorer.py
+++ b/marimo/_plugins/ui/_impl/data_explorer.py
@@ -8,6 +8,7 @@ from marimo._plugins.ui._impl.tables.utils import get_table_manager
if TYPE_CHECKING:
import pandas as pd
import polars as pl
+ import pyarrow as pa
import marimo._output.data.data as mo_data
@@ -39,7 +40,7 @@ class data_explorer(UIElement[Dict[str, Any], Dict[str, Any]]):
def __init__(
self,
- df: Union[pd.DataFrame, pl.DataFrame],
+ df: Union[pd.DataFrame, pl.DataFrame, pa.Table],
on_change: Optional[Callable[[Dict[str, Any]], None]] = None,
) -> None:
self._data = df
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 0355e59283..75535c8e87 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -16,7 +16,6 @@ from typing import (
import marimo._output.data.data as mo_data
from marimo import _loggers
-from marimo._dependencies.dependencies import DependencyManager
from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
@@ -159,18 +158,15 @@ class table(
self._manager = get_table_manager(data)
self._filtered_manager: Optional[TableManager[Any]] = None
- totalRows = len(self._manager.data)
+ totalRows = self._manager.get_num_rows()
hasMore = totalRows > TableManager.DEFAULT_LIMIT
if hasMore:
self._manager = self._manager.limit(TableManager.DEFAULT_LIMIT)
# pagination defaults to True if there are more than 10 rows
if pagination is None:
- pagination = len(self._data) > 10
+ pagination = totalRows > 10
- can_download = (
- DependencyManager.has_pandas() or DependencyManager.has_polars()
- )
field_types = self._manager.get_field_types()
super().__init__(
@@ -184,8 +180,10 @@ class table(
"pagination": pagination,
"page-size": page_size,
"field-types": field_types if field_types else None,
- "selection": selection,
- "show-download": can_download,
+ "selection": selection
+ if self._manager.supports_selection()
+ else None,
+ "show-download": self._manager.supports_download(),
"row-headers": self._manager.get_row_headers(),
},
on_change=on_change,
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index f2eadcec7d..2cc7c34fcf 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -20,6 +20,9 @@ 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 TableManager
JsonTableData = Union[
@@ -36,6 +39,14 @@ class DefaultTableManager(TableManager[JsonTableData]):
def __init__(self, data: JsonTableData):
self.data = data
+ def supports_download(self) -> bool:
+ # If we have pandas/polars/pyarrow, we can convert to CSV or JSON
+ return (
+ DependencyManager.has_pandas()
+ or DependencyManager.has_polars()
+ or DependencyManager.has_pyarrow()
+ )
+
def to_data(self) -> JSONType:
return self._normalize_data(self.data)
@@ -77,6 +88,16 @@ class DefaultTableManager(TableManager[JsonTableData]):
import polars as pl
return PolarsTableManagerFactory.create()(pl.DataFrame(self.data))
+ if DependencyManager.has_pyarrow():
+ import pyarrow as pa
+
+ if isinstance(self.data, dict):
+ return PyArrowTableManagerFactory.create()(
+ pa.Table.from_pydict(self.data)
+ )
+ return PyArrowTableManagerFactory.create()(
+ pa.Table.from_pylist(self._normalize_data(self.data))
+ )
raise ValueError("No supported table libraries found.")
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index f79c8c60eb..8dbf31e018 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -31,6 +31,15 @@ class TableManager(abc.ABC, Generic[T]):
"""
return mo_data.csv(self.to_csv()).url
+ def supports_download(self) -> bool:
+ return True
+
+ def supports_selection(self) -> bool:
+ return True
+
+ def supports_altair(self) -> bool:
+ return True
+
@abc.abstractmethod
def to_csv(self) -> bytes:
raise NotImplementedError
@@ -73,9 +82,6 @@ class TableManager(abc.ABC, Generic[T]):
def get_num_columns(self) -> int:
raise NotImplementedError
- def supports_altair(self) -> bool:
- return True
-
class TableManagerFactory(abc.ABC):
@staticmethod
diff --git a/marimo/_plugins/ui/_impl/tables/types.py b/marimo/_plugins/ui/_impl/tables/types.py
new file mode 100644
index 0000000000..dc297f9683
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/tables/types.py
@@ -0,0 +1,11 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any, Protocol, runtime_checkable
+
+
+@runtime_checkable
+class DataFrameLike(Protocol):
+ def __dataframe__(
+ self, nan_as_null: bool = False, allow_copy: bool = True
+ ) -> Any: ...
diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.py
index da006806df..84b0913379 100644
--- a/marimo/_plugins/ui/_impl/tables/utils.py
+++ b/marimo/_plugins/ui/_impl/tables/utils.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, List
+from typing import TYPE_CHECKING, Any, List
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.default_table import DefaultTableManager
@@ -18,6 +18,10 @@ from marimo._plugins.ui._impl.tables.table_manager import (
TableManager,
TableManagerFactory,
)
+from marimo._plugins.ui._impl.tables.types import DataFrameLike
+
+if TYPE_CHECKING:
+ import pyarrow
MANAGERS: List[TableManagerFactory] = [
PandasTableManagerFactory(),
@@ -31,10 +35,52 @@ def get_table_manager(data: Any) -> TableManager[Any]:
def get_table_manager_or_none(data: Any) -> TableManager[Any] | None:
+ if data is None:
+ return None
+
+ # Try to find a manager specifically for the data type
for manager_factory in MANAGERS:
if DependencyManager.has(manager_factory.package_name()):
manager = manager_factory.create()
if manager.is_type(data):
return manager(data)
+ # If we have a DataFrameLike object, try to convert it the pyarrow table
+ if isinstance(data, DataFrameLike):
+ DependencyManager.require_pyarrow(
+ "For table support using the dataframe protocol"
+ )
+ return PyArrowTableManagerFactory.create()(
+ arrow_table_from_dataframe_protocol(data)
+ )
+
return None
+
+
+# Copied from Altair
+# https://github.com/vega/altair/blob/18a2c3c237014591d172284560546a2f0ac1a883/altair/utils/data.py#L343
+def arrow_table_from_dataframe_protocol(
+ dfi_df: DataFrameLike,
+) -> "pyarrow.lib.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[no-any-return]
diff --git a/marimo/_smoke_tests/dataframe.py b/marimo/_smoke_tests/dataframe.py
index c9285a39d3..b7db31f929 100644
--- a/marimo/_smoke_tests/dataframe.py
+++ b/marimo/_smoke_tests/dataframe.py
@@ -2,11 +2,11 @@
import marimo
-__generated_with = "0.3.10"
+__generated_with = "0.6.12"
app = marimo.App(width="full")
[email protected](hide_code=True)
def __(mo):
mo.md("# 🤖 Lists/Dicts")
return
@@ -61,13 +61,13 @@ def __(as_primitives):
return
[email protected](hide_code=True)
def __(mo):
mo.md("# 🐼 Pandas")
return
[email protected](hide_code=True)
def __(mo):
mo.md("## mo.ui.dataframe")
return
@@ -80,7 +80,7 @@ def __(cars, mo):
return dataframe,
[email protected](hide_code=True)
def __(mo):
mo.md("## mo.ui.table")
return
@@ -92,7 +92,7 @@ def __(dataframe, mo):
return
[email protected](hide_code=True)
def __(mo):
mo.md("## .value")
return
@@ -110,7 +110,7 @@ def __(dataframe):
return
[email protected](hide_code=True)
def __(mo):
mo.md("## mo.ui.data_explorer")
return
@@ -122,13 +122,13 @@ def __(mo, pl_dataframe):
return
[email protected](hide_code=True)
def __(mo):
mo.md("# 🐻‍❄️ Polars")
return
[email protected](hide_code=True)
def __(mo):
mo.md("## mo.ui.table")
return
@@ -141,7 +141,7 @@ def __(cars, mo, pl):
return pl_dataframe,
[email protected](hide_code=True)
def __(mo):
mo.md("## mo.ui.data_explorer")
return
@@ -153,7 +153,7 @@ def __(mo, pl_dataframe):
return
[email protected](hide_code=True)
def __(mo):
mo.md("# 🏹 Arrow")
return
@@ -166,7 +166,7 @@ def __(cars, mo, pa):
return arrow_table,
[email protected](hide_code=True)
def __(mo):
mo.md("## mo.ui.table")
return
@@ -179,7 +179,7 @@ def __(arrow_table, mo):
return arrow_table_el,
[email protected](hide_code=True)
def __(mo):
mo.md("## .value")
return
@@ -191,6 +191,74 @@ def __(arrow_table_el):
return
+def __(arrow_table, mo):
+ mo.ui.data_explorer(arrow_table)
+ return
+
+
+def __(mo):
+ mo.md(
+ rf"""
+ # 💽 Dataframe protocol
+ > See the [API](https://data-apis.org/dataframe-protocol/latest/API.html)
+ """
+ )
+ return
+
+
+def __(dask_dfda):
+ import dask.dataframe as dd
+
+ dask_df = dd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
+ dask_dfda
+ return dask_df, dd
+
+
+def __():
+ import ibis
+
+ ibis.options.interactive = True
+
+ ibis_data = ibis.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv", table_name="penguins")
+ ibis_data
+ return ibis, ibis_data
+
+
+def __(mo):
+ mo.md(rf"## mo.ui.table")
+ return
+
+
+def __(ibis_data, mo):
+ ibis_penguins = mo.ui.table(ibis_data)
+ ibis_penguins
+ return ibis_penguins,
+
+
+def __(ibis_penguins):
+ ibis_penguins.value
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(rf"## mo.ui.data_explorer")
+ return
+
+
+def __(ibis_data, mo):
+ mo.ui.data_explorer(ibis_data)
+ return
+
+
@app.cell
def __():
import marimo as mo
@@ -198,9 +266,10 @@ def __():
import polars as pl
import pyarrow as pa
import vega_datasets
+ import altair as alt
cars = vega_datasets.data.cars()
- return cars, mo, pa, pd, pl, vega_datasets
+ return alt, cars, mo, pa, pd, pl, vega_datasets
if __name__ == "__main__":