A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: add .from_series to many mo.ui inputs (#1678)
Myles Scolnicked124bf56422
diff --git a/marimo/_data/series.py b/marimo/_data/series.pynew file mode 100644index 0000000000..506d5061da--- /dev/null+++ b/marimo/_data/series.py@@ -0,0 +1,142 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import datetime+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Union++from marimo._dependencies.dependencies import DependencyManager++if TYPE_CHECKING:+ import pandas as pd+ import polars as pl++DataFrameSeries = Union["pd.Series[Any]", "pl.Series"]+++@dataclass+class NumberSeriesInfo:+ """+ Represents a summary of a numeric series.+ """++ min: float+ max: float+ label: str+++@dataclass+class CategorySeriesInfo:+ """+ Represents a summary of a categorical series.+ """++ categories: list[str]+ label: str+++@dataclass+class DateSeriesInfo:+ """+ Represents a summary of a date series.+ """++ min: str+ max: str+ label: str+++def _get_name(series: DataFrameSeries) -> str:+ return str(series.name) if series.name is not None else ""+++def get_number_series_info(series: Any) -> NumberSeriesInfo:+ """+ Get the summary of a numeric series.+ """++ def validate_number(value: Any) -> float:+ value = float(value)+ if not isinstance(value, (int, float)):+ raise ValueError("Expected a number. Got: " + str(type(value)))+ return value++ if DependencyManager.has_pandas():+ import pandas as pd++ if isinstance(series, pd.Series):+ return NumberSeriesInfo(+ min=validate_number(series.min()),+ max=validate_number(series.max()),+ label=_get_name(series),+ )++ if DependencyManager.has_polars():+ import polars as pl++ if isinstance(series, pl.Series):+ return NumberSeriesInfo(+ min=validate_number(series.min()),+ max=validate_number(series.max()),+ label=_get_name(series),+ )++ raise ValueError("Unsupported series type. Expected pandas or polars.")+++def get_category_series_info(series: Any) -> CategorySeriesInfo:+ """+ Get the summary of a categorical series.+ """+ if DependencyManager.has_pandas():+ import pandas as pd++ if isinstance(series, pd.Series):+ return CategorySeriesInfo(+ categories=sorted(series.unique().tolist()),+ label=_get_name(series),+ )++ if DependencyManager.has_polars():+ import polars as pl++ if isinstance(series, pl.Series):+ return CategorySeriesInfo(+ categories=sorted(series.unique().to_list()),+ label=_get_name(series),+ )++ raise ValueError("Unsupported series type. Expected pandas or polars.")+++def get_date_series_info(series: Any) -> DateSeriesInfo:+ """+ Get the summary of a date series.+ """++ def validate_date(value: Any) -> str:+ if not isinstance(value, datetime.date):+ raise ValueError("Expected a date. Got: " + str(type(value)))+ return value.strftime("%Y-%m-%d")++ if DependencyManager.has_pandas():+ import pandas as pd++ if isinstance(series, pd.Series):+ return DateSeriesInfo(+ min=validate_date(series.min()),+ max=validate_date(series.max()),+ label=_get_name(series),+ )++ if DependencyManager.has_polars():+ import polars as pl++ if isinstance(series, pl.Series):+ return DateSeriesInfo(+ min=validate_date(series.min()),+ max=validate_date(series.max()),+ label=_get_name(series),+ )++ raise ValueError("Unsupported series type. Expected pandas or polars.")diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex 658d2e5820..b5f19e07fe 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -23,6 +23,12 @@ from typing import ()from marimo import _loggers+from marimo._data.series import (+ DataFrameSeries,+ get_category_series_info,+ get_date_series_info,+ get_number_series_info,+)from marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import S as JSONTypeBound, UIElement@@ -46,6 +52,12 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):number = mo.ui.number(start=1, stop=10, step=2)```+ Or from a dataframe series:++ ```python+ number = mo.ui.number.from_series(df["column_name"])+ ```+**Attributes.**- `value`: the value of the number, possibly `None`@@ -113,6 +125,14 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):on_change=on_change,)+ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "number":+ """Create a number picker from a dataframe series."""+ info = get_number_series_info(series)+ return number(+ start=info.min, stop=info.max, label=info.label, **kwargs+ )+def _convert_value(self, value: Optional[Numeric]) -> Optional[Numeric]:"""Value is `None` if user uses keyboard to delete contents of input"""return value@@ -129,6 +149,12 @@ class slider(UIElement[Numeric, Numeric]):slider = mo.ui.slider(start=1, stop=10, step=2)```+ Or from a dataframe series:++ ```python+ slider = mo.ui.slider.from_series(df["column_name"])+ ```+**Attributes.**- `value`: the current numeric value of the slider@@ -280,6 +306,14 @@ class slider(UIElement[Numeric, Numeric]):on_change=on_change,)+ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "slider":+ """Create a slider from a dataframe series."""+ info = get_number_series_info(series)+ return slider(+ start=info.min, stop=info.max, label=info.label, **kwargs+ )+def _convert_value(self, value: Numeric) -> Numeric:if self._mapping is not None:return cast(Numeric, self._dtype(self._mapping[int(value)]))@@ -297,6 +331,12 @@ class range_slider(UIElement[List[Numeric], Sequence[Numeric]]):range_slider = mo.ui.range_slider(start=1, stop=10, step=2, value=[2, 6])```+ Or from a dataframe series:++ ```python+ range_slider = mo.ui.range_slider.from_series(df["column_name"])+ ```+**Attributes.**- `value`: the current range value of the slider@@ -446,6 +486,14 @@ class range_slider(UIElement[List[Numeric], Sequence[Numeric]]):on_change=on_change,)+ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "range_slider":+ """Create a range slider from a dataframe series."""+ info = get_number_series_info(series)+ return range_slider(+ start=info.min, stop=info.max, label=info.label, **kwargs+ )+def _convert_value(self, value: List[Numeric]) -> Sequence[Numeric]:if self._mapping is not None:return cast(@@ -532,6 +580,12 @@ class radio(UIElement[Optional[str], Any]):)```+ Or from a dataframe series:++ ```python+ radiogroup = mo.ui.radio.from_series(df["column_name"])+ ```+**Attributes.**- `value`: the value of the selected radio option@@ -573,6 +627,16 @@ class radio(UIElement[Optional[str], Any]):on_change=on_change,)+ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "radio":+ """Create a radio group from a dataframe series."""+ info = get_category_series_info(series)+ return radio(+ options=info.categories,+ label=info.label,+ **kwargs,+ )+def _convert_value(self, value: Optional[str]) -> Any:return self.options[value] if value is not None else None@@ -780,6 +844,12 @@ class dropdown(UIElement[List[str], Any]):)```+ Or from a dataframe series:++ ```python+ dropdown = mo.ui.dropdown.from_series(df["column_name"])+ ```+**Attributes.**- `value`: the selected value, or `None` if no selection@@ -856,6 +926,16 @@ class dropdown(UIElement[List[str], Any]):on_change=on_change,)+ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "dropdown":+ """Create a dropdown from a dataframe series."""+ info = get_category_series_info(series)+ return dropdown(+ options=info.categories,+ label=info.label,+ **kwargs,+ )+def _convert_value(self, value: list[str]) -> Any:if value:assert len(value) == 1@@ -884,6 +964,12 @@ class multiselect(UIElement[List[str], List[object]]):)```+ Or from a dataframe series:++ ```python+ multiselect = mo.ui.multiselect.from_series(df["column_name"])+ ```+**Attributes.**- `value`: the selected values, or `None` if no selection@@ -951,6 +1037,16 @@ class multiselect(UIElement[List[str], List[object]]):on_change=on_change,)+ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "multiselect":+ """Create a multiselect from a dataframe series."""+ info = get_category_series_info(series)+ return multiselect(+ options=info.categories,+ label=info.label,+ **kwargs,+ )+def _convert_value(self, value: list[str]) -> list[object]:return [self.options[v] for v in value]@@ -1350,6 +1446,12 @@ class date(UIElement[str, dt.date]):)```+ Or from a dataframe series:++ ```python+ date = mo.ui.date.from_series(df["column_name"])+ ```+**Attributes.**- `value`: a str (YYYY-MM-DD) or `datetime.date` object of the chosen date@@ -1428,6 +1530,17 @@ class date(UIElement[str, dt.date]):on_change=on_change,)+ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "date":+ """Create a date picker from a dataframe series."""+ info = get_date_series_info(series)+ return date(+ start=info.min,+ stop=info.max,+ label=info.label,+ **kwargs,+ )+def _convert_value(self, value: str) -> dt.date:return dt.datetime.strptime(value, self.DATEFORMAT).date()diff --git a/marimo/_smoke_tests/from_series.py b/marimo/_smoke_tests/from_series.pynew file mode 100644index 0000000000..2842ff892b--- /dev/null+++ b/marimo/_smoke_tests/from_series.py@@ -0,0 +1,78 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.6.23"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ from vega_datasets import data+ return data, mo+++def __(data):+ import polars as pl+ polars_df = pl.from_pandas(data.cars())+ return pl, polars_df+++def __(mo, polars_df):+ mo.ui.slider.from_series(polars_df["Cylinders"])+ return+++def __(mo, polars_df):+ mo.ui.number.from_series(polars_df["Cylinders"])+ return+++def __(mo, polars_df):+ mo.ui.radio.from_series(polars_df["Origin"])+ return+++def __(mo, polars_df):+ mo.ui.dropdown.from_series(polars_df["Origin"])+ return+++def __(mo, polars_df):+ mo.ui.multiselect.from_series(polars_df["Origin"])+ return+++def __(mo, polars_df):+ mo.ui.date.from_series(polars_df["Year"])+ return+++def __(data, mo):+ pandas_df = data.cars()+ [+ mo.ui.slider.from_series(pandas_df["Cylinders"]),+ mo.ui.number.from_series(pandas_df["Cylinders"]),+ mo.ui.radio.from_series(pandas_df["Origin"]),+ mo.ui.dropdown.from_series(pandas_df["Origin"]),+ mo.ui.multiselect.from_series(pandas_df["Origin"]),+ mo.ui.date.from_series(pandas_df["Year"])+ ]+ return pandas_df,+++def __():+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_data/test_series.py b/tests/_data/test_series.pynew file mode 100644index 0000000000..443422332f--- /dev/null+++ b/tests/_data/test_series.py@@ -0,0 +1,115 @@+from __future__ import annotations++from datetime import datetime+from typing import Any+from unittest.mock import Mock++import pytest++from marimo._data.series import (+ get_category_series_info,+ get_date_series_info,+ get_number_series_info,+)+from marimo._dependencies.dependencies import DependencyManager++HAS_DEPS = (+ DependencyManager.has_pandas()+ and DependencyManager.has_numpy()+ and DependencyManager.has_polars()+)++if HAS_DEPS:+ import pandas as pd+ import polars as pl+else:+ pd = Mock()+ pl = Mock()++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ [+ pd.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]}),+ pl.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]}),+ ],+)+def test_number_series(+ df: Any,+) -> None:+ response = get_number_series_info(df["A"])++ assert response.min == 1+ assert response.max == 3+ assert response.label == "A"++ with pytest.raises(ValueError):+ response = get_number_series_info(df["B"])++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_get_with_no_name() -> None:+ series = pd.Series([1, 2, 3])+ series.name = None+ assert get_number_series_info(series).label == ""++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ [+ pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "b"]}),+ pl.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "b"]}),+ ],+)+def test_categorical_series(df: Any) -> None:+ response = get_category_series_info(df["B"])++ assert response.categories == ["a", "b"]+ assert response.label == "B"++ response = get_category_series_info(df["A"])+ assert response.categories == [1, 2, 3]+ assert response.label == "A"++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ [+ pd.DataFrame(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "b"],+ "C": [+ datetime(2024, 1, 1),+ datetime(2024, 1, 2),+ datetime(2024, 1, 3),+ ],+ }+ ),+ pl.DataFrame(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "b"],+ "C": [+ datetime(2024, 1, 1),+ datetime(2024, 1, 2),+ datetime(2024, 1, 3),+ ],+ }+ ),+ ],+)+def test_date_series(df: Any) -> None:+ response = get_date_series_info(df["C"])++ assert response.min == "2024-01-01"+ assert response.max == "2024-01-03"+ assert response.label == "C"++ with pytest.raises(ValueError):+ response = get_date_series_info(df["B"])+ with pytest.raises(ValueError):+ response = get_date_series_info(df["A"])diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.pyindex 1a9f6ee6b5..5a694640fd 100644--- a/tests/_plugins/ui/_impl/test_input.py+++ b/tests/_plugins/ui/_impl/test_input.py@@ -1,12 +1,16 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import datetimefrom typing import Anyimport pytest+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins import ui+HAS_PANDAS = DependencyManager.has_pandas()+def test_number_init() -> None:number = ui.number(1, 10)@@ -47,6 +51,18 @@ def test_number_invalid_bounds() -> None:assert "Invalid bounds" in str(e.value)[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_number_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame({"A": [1, 2, 3]})+ number = ui.number.from_series(df["A"], step=0.1)+ assert number.start == 1+ assert number.stop == 3+ assert number.value == 1+ assert number.step == 0.1++def test_slider_init() -> None:slider = ui.slider(1, 10)assert slider.start == 1@@ -129,6 +145,18 @@ def test_slider_out_of_bounds() -> None:assert "out of bounds" in str(e.value)[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_slider_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame({"A": [1, 2, 3]})+ slider = ui.slider.from_series(df["A"], step=0.1)+ assert slider.start == 1+ assert slider.stop == 3+ assert slider.value == 1+ assert slider.step == 0.1++def test_range_slider_init() -> None:slider = ui.range_slider(1, 10)assert slider.start == 1@@ -214,6 +242,18 @@ def test_range_slider_out_of_bounds() -> None:assert "out of bounds" in str(e.value)[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_range_slider_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame({"A": [1, 2, 3]})+ slider = ui.range_slider.from_series(df["A"], step=0.1)+ assert slider.start == 1+ assert slider.stop == 3+ assert slider.value == [1, 3]+ assert slider.step == 0.1++def test_text() -> None:assert ui.text().value == ""assert ui.text(value="hello world").value == "hello world"@@ -242,6 +282,20 @@ def test_radio() -> None:assert radio.value == 2[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_radio_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame({"A": ["a", "b", "c"]})+ radio = ui.radio.from_series(df["A"], value="b")+ assert radio.options == {+ "a": "a",+ "b": "b",+ "c": "c",+ }+ assert radio.value == "b"++def test_dropdown() -> None:dd = ui.dropdown(options=["1", "2", "3"])assert dd.value is None@@ -263,6 +317,20 @@ def test_dropdown_too_many_options() -> None:assert "maximum number" in str(e.value)[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_dropdown_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame({"A": ["a", "b", "c"]})+ dd = ui.dropdown.from_series(df["A"], value="b")+ assert dd.options == {+ "a": "a",+ "b": "b",+ "c": "c",+ }+ assert dd.value == "b"++def test_multiselect() -> None:options_list = ["Apples", "Oranges", "Bananas"]ms = ui.multiselect(options=options_list)@@ -308,6 +376,20 @@ def test_multiselect_too_many_options() -> None:assert "maximum number" in str(e.value)[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_multiselect_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame({"A": ["a", "b", "c"]})+ ms = ui.multiselect.from_series(df["A"], value=["b"])+ assert ms.options == {+ "a": "a",+ "b": "b",+ "c": "c",+ }+ assert ms.value == ["b"]++def test_button() -> None:assert ui.button().value is Noneassert ui.button(value=1).value == 1@@ -345,4 +427,32 @@ def test_form_in_array_retains_on_change() -> None:# TODO(akshayka): test file-# TODO(akshayka): test date+++def test_date() -> None:+ date = ui.date()+ today = date.value+ assert today == datetime.date.today()++ date._update("2024-01-01")+ assert date.value == datetime.date(2024, 1, 1)++ date = ui.date(value="2024-01-01")+ assert date.value == datetime.date(2024, 1, 1)++ date = ui.date(value="2024-01-01")+ date._update("2024-01-02")+ assert date.value == datetime.date(2024, 1, 2)++[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_date_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame(+ {"A": [pd.Timestamp("2024-01-01"), pd.Timestamp("2024-01-02")]}+ )+ date = ui.date.from_series(df["A"], value=datetime.date(2024, 1, 2))+ assert date.value == datetime.date(2024, 1, 2)+ assert date.start == datetime.date(2024, 1, 1)+ assert date.stop == datetime.date(2024, 1, 2)