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: auto-encoding pandas/numpy, mo.ui.table takes in Dataframe (#197)

Myles Scolnickd089776a5a46
diff --git a/docs/api/inputs/table.md b/docs/api/inputs/table.md
index d7e7fce7b1..f160bf733c 100644
--- a/docs/api/inputs/table.md
+++ b/docs/api/inputs/table.md
@@ -6,5 +6,5 @@
.. autoclass:: marimo.ui.table
:members:
- .. autoclasstoc:: marimo._plugins.ui._impl.input.table
+ .. autoclasstoc:: marimo._plugins.ui._impl.table.table
```
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index ca9e194c0b..76721e684c 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -22,6 +22,21 @@ class DependencyManager:
+ "You can install it with 'pip install pandas'"
) from None
+ @staticmethod
+ def require_numpy(why: str) -> None:
+ """
+ Raise an ModuleNotFoundError if numpy is not installed.
+
+ Args:
+ why: A string of the form "for <reason>" that will be appended
+
+ """
+ if not DependencyManager.has_numpy():
+ raise ModuleNotFoundError(
+ f"numpy is required {why}. "
+ + "You can install it with 'pip install numpy'"
+ ) from None
+
@staticmethod
def require_altair(why: str) -> None:
"""
@@ -42,6 +57,11 @@ class DependencyManager:
"""Return True if pandas is installed."""
return importlib.util.find_spec("pandas") is not None
+ @staticmethod
+ def has_numpy() -> bool:
+ """Return True if numpy is installed."""
+ return importlib.util.find_spec("numpy") is not None
+
@staticmethod
def has_altair() -> bool:
"""Return True if altair is installed."""
diff --git a/marimo/_plugins/core/json_encoder.py b/marimo/_plugins/core/json_encoder.py
index 209c174257..6c2ad15baf 100644
--- a/marimo/_plugins/core/json_encoder.py
+++ b/marimo/_plugins/core/json_encoder.py
@@ -2,14 +2,44 @@
from json import JSONEncoder
from typing import Any
+from marimo._dependencies.dependencies import DependencyManager
+
class WebComponentEncoder(JSONEncoder):
"""Custom JSON encoder for WebComponents"""
def default(self, obj: Any) -> Any:
+ # Handle numpy objects
+ if DependencyManager.has_numpy():
+ import numpy as np
+
+ dtypes = (np.datetime64, np.complexfloating)
+ if isinstance(obj, dtypes):
+ return str(obj)
+ elif isinstance(obj, np.integer):
+ return int(obj)
+ elif isinstance(obj, np.floating):
+ return float(obj)
+ elif isinstance(obj, np.ndarray):
+ if any([np.issubdtype(obj.dtype, i) for i in dtypes]):
+ return obj.astype(str).tolist()
+ return obj.tolist()
+
+ # Handle pandas objects
+ if DependencyManager.has_pandas():
+ import pandas as pd
+
+ if isinstance(obj, pd.DataFrame):
+ return obj.to_dict("records")
+ elif isinstance(obj, pd.Series):
+ return obj.to_list()
+ elif isinstance(obj, pd.Timestamp):
+ return str(obj)
+
# Handle MIME objects
if hasattr(obj, "_mime_"):
(mimetype, data) = obj._mime_()
return {"mimetype": mimetype, "data": data}
+
# Fallthrough to default encoder
return JSONEncoder.default(self, obj)
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index 753dc656f0..55746ac763 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -43,10 +43,10 @@ from marimo._plugins.ui._impl.input import (
number,
radio,
slider,
- table,
text,
text_area,
)
from marimo._plugins.ui._impl.microphone import microphone
from marimo._plugins.ui._impl.refresh import refresh
from marimo._plugins.ui._impl.switch import switch
+from marimo._plugins.ui._impl.table import table
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index 517ff154ae..71c07a1d57 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -20,7 +20,6 @@ from typing import (
)
from marimo import _loggers
-from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import S as JSONTypeBound
from marimo._plugins.ui._core.ui_element import UIElement
@@ -591,107 +590,6 @@ class multiselect(UIElement[List[str], List[object]]):
return [self.options[v] for v in value]
-@mddoc
-class table(UIElement[List[str], List[object]]):
- """
- A table component.
-
- **Example.**
-
- ```python
- table = mo.ui.table(
- data=[
- {'first_name': 'Michael', 'last_name': 'Scott'},
- {'first_name': 'Dwight', 'last_name': 'Schrute'}
- ],
- label='Users'
- )
- ```
-
- ```python
- # df is a Pandas dataframe
- table = mo.ui.table(
- data=df.to_dict('records'),
- # use pagination when your table has many rows
- pagination=True,
- label='Dataset'
- )
- ```
-
- **Attributes.**
-
- - `value`: the selected values, or `None` if no selection.
- - `data`: the table data
-
- **Initialization Args.**
-
- - `data`: a list of values representing a column, or a list of dicts
- where each dict represents a row in the table
- (mapping column names to values). values can be
- primitives (`str`, `int`, `float`, `bool`, or `None`)
- or Marimo elements: e.g.
- `mo.ui.button(...)`, `mo.md(...)`, `mo.as_html(...)`, etc.
- - `pagination`: whether to paginate; if `False`, all rows will be shown
- - `selection`: 'single' or 'multi' to enable row selection, or `None` to
- disable
- - `label`: text label for the element
- - `on_change`: optional callback to run when this element's value changes
- """
-
- _name: Final[str] = "marimo-table"
-
- def __init__(
- self,
- data: Sequence[str | int | float | bool | MIME | None]
- | Sequence[dict[str, str | int | float | bool | MIME | None]],
- pagination: bool = False,
- selection: Optional[Literal["single", "multi"]] = "multi",
- *,
- label: str = "",
- on_change: Optional[Callable[[List[object]], None]] = None,
- ) -> None:
- if not isinstance(data, (list, tuple)):
- raise ValueError("data must be a list or tuple.")
-
- self._data = data
- if not isinstance(data[0], dict) and isinstance(
- data[0], (str, int, float, bool, type(None))
- ):
- # we're going to assume that data has the right shape, after
- # having checked just the first entry
- data = cast(List[Union[str, int, float, bool, MIME, None]], data)
- data = [{"value": datum} for datum in data]
- elif not isinstance(data[0], dict):
- raise ValueError(
- "data must be a sequence of JSON-serializable types, or a "
- "sequence of dicts."
- )
-
- super().__init__(
- component_name=table._name,
- label=label,
- initial_value=[],
- args={
- "data": data,
- "pagination": pagination,
- "selection": selection,
- },
- on_change=on_change,
- )
-
- @property
- def data(
- self,
- ) -> Union[
- Sequence[str | int | float | bool | None],
- Sequence[dict[str, str | int | float | bool | None]],
- ]:
- return self._data
-
- def _convert_value(self, value: list[str]) -> list[object]:
- return [self._data[int(v)] for v in value]
-
-
@mddoc
class button(UIElement[Any, Any]):
"""
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
new file mode 100644
index 0000000000..3c43a40e18
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -0,0 +1,157 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ Dict,
+ Final,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Union,
+ cast,
+)
+
+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
+from marimo._plugins.ui._core.ui_element import UIElement
+
+LOGGER = _loggers.marimo_logger()
+
+Numeric = Union[int, float]
+
+if TYPE_CHECKING:
+ import pandas as pd
+
+TableData = Union[
+ Sequence[Union[str, int, float, bool, MIME, None]],
+ Sequence[Dict[str, Union[str, int, float, bool, MIME, None]]],
+ "pd.DataFrame",
+]
+
+
+@mddoc
+class table(UIElement[List[str], List[object]]):
+ """
+ A table component.
+
+ **Example.**
+
+ ```python
+ table = mo.ui.table(
+ data=[
+ {'first_name': 'Michael', 'last_name': 'Scott'},
+ {'first_name': 'Dwight', 'last_name': 'Schrute'}
+ ],
+ label='Users'
+ )
+ ```
+
+ ```python
+ # df is a Pandas dataframe
+ table = mo.ui.table(
+ data=df,
+ # use pagination when your table has many rows
+ pagination=True,
+ label='Dataset'
+ )
+ ```
+
+ **Attributes.**
+
+ - `value`: the selected values, or `None` if no selection.
+ - `data`: the table data
+
+ **Initialization Args.**
+
+ - `data`: A pandas dataframe, or a list of values representing a column,
+ or a list of dicts where each dict represents a row in the table
+ (mapping column names to values). values can be
+ primitives (`str`, `int`, `float`, `bool`, or `None`)
+ or Marimo elements: e.g.
+ `mo.ui.button(...)`, `mo.md(...)`, `mo.as_html(...)`, etc.
+ - `pagination`: whether to paginate; if `False`, all rows will be shown
+ defaults to `True` when above 10 rows, `False` otherwise
+ - `selection`: 'single' or 'multi' to enable row selection, or `None` to
+ disable
+ - `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
+ """
+
+ _name: Final[str] = "marimo-table"
+
+ def __init__(
+ self,
+ data: Union[
+ Sequence[Union[str, int, float, bool, MIME, None]],
+ Sequence[Dict[str, Union[str, int, float, bool, MIME, None]]],
+ "pd.DataFrame",
+ ],
+ pagination: Optional[bool] = None,
+ selection: Optional[Literal["single", "multi"]] = "multi",
+ *,
+ label: str = "",
+ on_change: Optional[Callable[[List[object]], None]] = None,
+ ) -> None:
+ self._data = data
+ normalized_data = _normalize_data(data)
+
+ # pagination defaults to True if there are more than 10 rows
+ if pagination is None:
+ pagination = len(self._data) > 10
+
+ super().__init__(
+ component_name=table._name,
+ label=label,
+ initial_value=[],
+ args={
+ "data": normalized_data,
+ "pagination": pagination,
+ "selection": selection,
+ },
+ on_change=on_change,
+ )
+
+ @property
+ def data(
+ self,
+ ) -> TableData:
+ return self._data
+
+ def _convert_value(self, value: list[str]) -> list[object]:
+ return [self._data[int(v)] for v in value]
+
+
+def _normalize_data(data: TableData) -> JSONType:
+ # Handle pandas
+ if DependencyManager.has_pandas():
+ import pandas as pd
+
+ if isinstance(data, pd.DataFrame):
+ return data.to_dict("records") # type: ignore
+
+ # Assert that data is a list
+ if not isinstance(data, (list, tuple)):
+ raise ValueError("data must be a list or tuple.")
+
+ # Handle single-column data
+ if not isinstance(data[0], dict) and isinstance(
+ data[0], (str, int, float, bool, type(None))
+ ):
+ # we're going to assume that data has the right shape, after
+ # having checked just the first entry
+ casted = cast(List[Union[str, int, float, bool, MIME, None]], data)
+ return [{"value": datum} for datum in casted]
+ elif not isinstance(data[0], dict):
+ raise ValueError(
+ "data must be a sequence of JSON-serializable types, or a "
+ "sequence of dicts."
+ )
+
+ # Sequence of dicts
+ return data
diff --git a/marimo/_plugins/ui/_impl/test_table.py b/marimo/_plugins/ui/_impl/test_table.py
new file mode 100644
index 0000000000..df0c212496
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/test_table.py
@@ -0,0 +1,71 @@
+# Copyright 2023 Marimo. All rights reserved.
+from typing import Any
+
+from marimo._plugins.ui._impl.table import TableData, _normalize_data
+
+
+def test_normalize_data() -> None:
+ data: TableData
+
+ # Test with list of integers
+ data = [1, 2, 3]
+ result = _normalize_data(data)
+ assert result == [
+ {"value": 1},
+ {"value": 2},
+ {"value": 3},
+ ]
+
+ # Test with list of strings
+ data = ["a", "b", "c"]
+ result = _normalize_data(data)
+ assert result == [
+ {"value": "a"},
+ {"value": "b"},
+ {"value": "c"},
+ ]
+
+ # Test with list of dictionaries
+ data = [
+ {"key1": "value1"},
+ {"key2": "value2"},
+ {"key3": "value3"},
+ ] # type: ignore
+ result = _normalize_data(data)
+ assert result == [
+ {"key1": "value1"},
+ {"key2": "value2"},
+ {"key3": "value3"},
+ ]
+
+ # Test with pandas DataFrame
+ try:
+ import pandas as pd
+
+ data = pd.DataFrame({"column1": [1, 2, 3], "column2": ["a", "b", "c"]})
+ result = _normalize_data(data)
+ assert result == [
+ {"column1": 1, "column2": "a"},
+ {"column1": 2, "column2": "b"},
+ {"column1": 3, "column2": "c"},
+ ]
+ except ImportError:
+ pass
+
+ # Test with invalid data type
+ data2: Any = "invalid data type"
+ try:
+ _normalize_data(data2)
+ except ValueError as e:
+ assert str(e) == "data must be a list or tuple."
+
+ # Test with invalid data structure
+ data3: Any = [set([1, 2, 3])]
+ try:
+ _normalize_data(data3)
+ except ValueError as e:
+ assert (
+ str(e)
+ == "data must be a sequence of JSON-serializable types, or a "
+ + "sequence of dicts."
+ )
diff --git a/marimo/_smoke_tests/charts/1mil_flights.py b/marimo/_smoke_tests/charts/1mil_flights.py
index ae32198fed..b78d952aca 100644
--- a/marimo/_smoke_tests/charts/1mil_flights.py
+++ b/marimo/_smoke_tests/charts/1mil_flights.py
@@ -1,3 +1,4 @@
+# Copyright 2023 Marimo. All rights reserved.
import marimo
__generated_with = "0.1.24"
@@ -10,7 +11,7 @@ def __(pd):
all_flights = pd.read_parquet(
"https://vegafusion-datasets.s3.amazonaws.com/vega/flights_1m.parquet"
)
- return all_flights,
+ return (all_flights,)
@app.cell
@@ -21,13 +22,13 @@ def __(mo):
value="100000",
)
size
- return size,
+ return (size,)
@app.cell
def __(all_flights, size):
flights = all_flights.sample(int(size.value))
- return flights,
+ return (flights,)
@app.cell
@@ -60,7 +61,7 @@ def __(alt, flights, mo):
alt.Chart(flights).mark_bar().encode(alt.X("delay"), alt.Y("count()"))
)
flight_histogram
- return flight_histogram,
+ return (flight_histogram,)
@app.cell
@@ -124,7 +125,9 @@ def __(airports, alt, data, flight_histogram, mo):
)
.transform_lookup(lookup="origin", from_=lookup_data)
.transform_lookup(
- lookup="destination", from_=lookup_data, as_=["state", "lat2", "lon2"]
+ lookup="destination",
+ from_=lookup_data,
+ as_=["state", "lat2", "lon2"],
)
.transform_filter(select_city)
)
@@ -141,7 +144,9 @@ def __(airports, alt, data, flight_histogram, mo):
)
.transform_aggregate(routes="count()", groupby=["origin"])
.transform_lookup(lookup="origin", from_=lookup_data)
- .transform_filter((alt.datum.state != "PR") & (alt.datum.state != "VI"))
+ .transform_filter(
+ (alt.datum.state != "PR") & (alt.datum.state != "VI")
+ )
.add_params(select_city)
)
@@ -169,9 +174,7 @@ def __(flight_histogram, mo):
f"Top airport: **{flight_histogram.value['origin'].value_counts().index[0]}**"
),
flight_histogram.value.describe(),
- # mo.ui.table(
- # flight_histogram.value.to_dict(orient="records"), pagination=False
- # ),
+ mo.ui.table(flight_histogram.value),
]
)
return
@@ -188,16 +191,17 @@ def __(alt, brush, flights, mo):
.add_params(brush)
)
mo.output.append(mo.ui.altair_chart(million_histogram))
- return million_histogram,
+ return (million_histogram,)
@app.cell
def __():
- import marimo as mo
- import pandas as pd
import altair as alt
+ import pandas as pd
from vega_datasets import data
+ import marimo as mo
+
airports = data.airports.url
None