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.

Add support for polars (#325)

Myles Scolnickabb9ef60d2a4
diff --git a/examples/third_party/polars.py b/examples/third_party/polars.py
new file mode 100644
index 0000000000..7fab1a8024
--- /dev/null
+++ b/examples/third_party/polars.py
@@ -0,0 +1,105 @@
+import marimo
+
+__generated_with = "0.1.47"
+app = marimo.App(width="full")
+
+
+def __(mo):
+ mo.md(
+ f"""
+ # Using `Polars` in `marimo`
+
+ > Lightning-fast DataFrame library for Rust and Python
+
+ `pip install polars`
+ """
+ )
+ return
+
+
+def __():
+ import marimo as mo
+ import polars as pl
+ import numpy as np
+ import altair as alt
+ return alt, mo, np, pl
+
+
+def __(pl):
+ df = pl.read_csv(
+ "https://gist.githubusercontent.com/ritchie46/cac6b337ea52281aa23c049250a4ff03/raw/89a957ff3919d90e6ef2d34235e6bf22304f3366/pokemon.csv"
+ )
+ return df,
+
+
+def __(df, mo):
+ # get all unique values
+ values_1 = df["Type 1"].unique().drop_nulls().to_list()
+ values_2 = df["Type 2"].unique().drop_nulls().to_list()
+
+ type_1_filter = mo.ui.dropdown(
+ options=values_1,
+ label="Type 1",
+ )
+ type_2_filter = mo.ui.dropdown(
+ options=values_2,
+ label="Type 2",
+ )
+
+
+ mo.hstack([type_1_filter, type_2_filter])
+ return type_1_filter, type_2_filter, values_1, values_2
+
+
+def __(alt, filtered, mo):
+ _chart = (
+ alt.Chart(filtered.to_pandas())
+ .mark_circle()
+ .encode(
+ x="Attack",
+ y="Defense",
+ size="Total",
+ color="Type 1",
+ tooltip=["Name", "Total", "Type 1", "Type 2"],
+ )
+ )
+
+ mo.ui.altair_chart(_chart, legend_selection=True, label="Attack vs Defense")
+ return
+
+
+def __(df, pl, type_1_filter, type_2_filter):
+ filtered = df
+ if type_1_filter.value:
+ filtered = filtered.filter(pl.col("Type 1") == type_1_filter.value)
+ if type_2_filter.value:
+ filtered = filtered.filter(pl.col("Type 2") == type_2_filter.value)
+ return filtered,
+
+
+def __(filtered, mo):
+ table = mo.ui.table(filtered)
+ table
+ return table,
+
+
+def __(mo, table):
+ mo.vstack(
+ [
+ mo.ui.table(table.value, label="Selected", selection=None),
+ table.value,
+ ]
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 76721e684c..c2c85625ad 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_polars(why: str) -> None:
+ """
+ Raise an ModuleNotFoundError if polars is not installed.
+
+ Args:
+ why: A string of the form "for <reason>" that will be appended
+
+ """
+ if not DependencyManager.has_polars():
+ raise ModuleNotFoundError(
+ f"polars is required {why}. "
+ + "You can install it with 'pip install polars'"
+ ) from None
+
@staticmethod
def require_numpy(why: str) -> None:
"""
@@ -57,6 +72,11 @@ class DependencyManager:
"""Return True if pandas is installed."""
return importlib.util.find_spec("pandas") is not None
+ @staticmethod
+ def has_polars() -> bool:
+ """Return True if polars is installed."""
+ return importlib.util.find_spec("polars") is not None
+
@staticmethod
def has_numpy() -> bool:
"""Return True if numpy is installed."""
diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.py
index 6b340e4301..8e9787cc9d 100644
--- a/marimo/_output/data/data.py
+++ b/marimo/_output/data/data.py
@@ -14,6 +14,7 @@ from marimo._runtime.virtual_file import (
if TYPE_CHECKING:
import pandas as pd
+ import polars as pl
def pdf(data: bytes) -> VirtualFile:
@@ -48,7 +49,9 @@ def image(data: bytes, ext: str = "png") -> VirtualFile:
return item.virtual_file
-def csv(data: Union[str, bytes, io.BytesIO, "pd.DataFrame"]) -> VirtualFile:
+def csv(
+ data: Union[str, bytes, io.BytesIO, "pd.DataFrame", "pl.DataFrame"]
+) -> VirtualFile:
"""Create a virtual file for CSV data.
**Args.**
@@ -70,10 +73,20 @@ def csv(data: Union[str, bytes, io.BytesIO, "pd.DataFrame"]) -> VirtualFile:
).encode("utf-8")
return any_data(buffer, ext="csv")
+ # Polars DataFrame
+ if DependencyManager.has_polars():
+ import polars as pl
+
+ if isinstance(data, pl.DataFrame):
+ buffer = data.write_csv().encode("utf-8")
+ return any_data(buffer, ext="csv")
+
return any_data(data, ext="csv") # type: ignore
-def json(data: Union[str, bytes, io.BytesIO, "pd.DataFrame"]) -> VirtualFile:
+def json(
+ data: Union[str, bytes, io.BytesIO, "pd.DataFrame", "pl.DataFrame"]
+) -> VirtualFile:
"""Create a virtual file for JSON data.
**Args.**
@@ -93,6 +106,14 @@ def json(data: Union[str, bytes, io.BytesIO, "pd.DataFrame"]) -> VirtualFile:
buffer = data.to_json(orient="records").encode("utf-8")
return any_data(buffer, ext="json")
+ # Polars DataFrame
+ if DependencyManager.has_polars():
+ import polars as pl
+
+ if isinstance(data, pl.DataFrame):
+ buffer = data.write_json(row_oriented=True).encode("utf-8")
+ return any_data(buffer, ext="json")
+
return any_data(data, ext="json") # type: ignore
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index e3389a6de8..455ac0c7d4 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -5,7 +5,6 @@ from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Callable,
- Dict,
Final,
List,
Literal,
@@ -31,6 +30,7 @@ Numeric = Union[int, float]
if TYPE_CHECKING:
import pandas as pd
+ import polars as pl
@dataclass
@@ -39,7 +39,9 @@ class DownloadAsArgs:
@mddoc
-class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
+class table(
+ UIElement[List[str], Union[List[JSONType], "pd.DataFrame", "pl.DataFrame"]]
+):
"""
A table component.
@@ -56,7 +58,7 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
```
```python
- # df is a Pandas dataframe
+ # df is a Pandas or Polars dataframe
table = mo.ui.table(
data=df,
# use pagination when your table has many rows
@@ -72,8 +74,9 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
**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
+ - `data`: A pandas dataframe, a polars dataframe,
+ 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.
@@ -94,8 +97,10 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
self,
data: Union[
Sequence[Union[str, int, float, bool, MIME, None]],
- Sequence[Dict[str, Union[str, int, float, bool, MIME, None]]],
+ Sequence[JSONType],
+ List[JSONType],
"pd.DataFrame",
+ "pl.DataFrame",
],
pagination: Optional[bool] = None,
selection: Optional[Literal["single", "multi"]] = "multi",
@@ -103,7 +108,9 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
*,
label: str = "",
on_change: Optional[
- Callable[[Union[List[object], "pd.DataFrame"]], None]
+ Callable[
+ [Union[List[JSONType], "pd.DataFrame", "pl.DataFrame"]], None
+ ]
] = None,
) -> None:
self._data = data
@@ -114,6 +121,10 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
if pagination is None:
pagination = len(self._data) > 10
+ can_download = (
+ DependencyManager.has_pandas() or DependencyManager.has_polars()
+ )
+
super().__init__(
component_name=table._name,
label=label,
@@ -123,7 +134,7 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
"pagination": pagination,
"page-size": page_size,
"selection": selection,
- "show-download": DependencyManager.has_pandas(),
+ "show-download": can_download,
"row-headers": get_row_headers(data),
},
on_change=on_change,
@@ -144,35 +155,74 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
def _convert_value(
self, value: list[str]
- ) -> Union[List[object], "pd.DataFrame"]:
+ ) -> Union[List[JSONType], "pd.DataFrame", "pl.DataFrame"]:
+ # Handle pandas
if DependencyManager.has_pandas():
import pandas as pd
if isinstance(self._data, pd.DataFrame):
return self._data.iloc[[int(v) for v in value]]
- return [self._data[int(v)] for v in value]
- def download_as(self, args: DownloadAsArgs) -> str:
- if not DependencyManager.has_pandas():
- raise RuntimeError("Pandas must be installed to download tables.")
+ # Handle polars
+ if DependencyManager.has_polars():
+ import polars as pl
- import pandas as pd
+ if isinstance(self._data, pl.DataFrame):
+ return self._data[[int(v) for v in value]]
- # download selected rows if there are any, otherwise use all rows
- data = self._value if len(self._value) > 0 else self._data
+ return [self._data[int(v)] for v in value] # type: ignore[misc]
- as_dataframe = (
- data
- if isinstance(data, pd.DataFrame)
- # TODO: fix types to remove type ignore
- else pd.DataFrame(self._normalized_data) # type:ignore[arg-type]
- )
+ def _as_data_frame(
+ self, data: TableData
+ ) -> Union["pd.DataFrame", "pl.DataFrame"]:
+ """
+ Convert the given data to the same type as the original data.
+ Otherwise, convert to whatever framework we have.
+ """
+ # Handle pandas
+ if DependencyManager.has_pandas():
+ import pandas as pd
+
+ # Make result a dataframe of the original type
+ if isinstance(self._data, pd.DataFrame) and not isinstance(
+ data, pd.DataFrame
+ ):
+ return pd.DataFrame(data) # type: ignore[arg-type]
+
+ # Handle polars
+ if DependencyManager.has_polars():
+ import polars as pl
+
+ # Make result a dataframe of the original type
+ if isinstance(self._data, pl.DataFrame) and not isinstance(
+ data, pl.DataFrame
+ ):
+ return pl.DataFrame(data)
+
+ # Convert to whatever framework we have
+
+ if DependencyManager.has_pandas():
+ import pandas as pd
+
+ return pd.DataFrame(data) # type: ignore[arg-type]
+
+ if DependencyManager.has_polars():
+ import polars as pl
+ return pl.DataFrame(data)
+
+ raise ValueError("Requires pandas or polars to be installed.")
+
+ def download_as(self, args: DownloadAsArgs) -> str:
+ # download selected rows if there are any, otherwise use all rows
+ data: TableData = self._value if len(self._value) > 0 else self._data
+
+ df = self._as_data_frame(data)
ext = args.format
if ext == "csv":
- return mo_data.csv(as_dataframe).url
+ return mo_data.csv(df).url
elif ext == "json":
- return mo_data.json(as_dataframe).url
+ return mo_data.json(df).url
else:
raise ValueError("format must be one of 'csv' or 'json'.")
@@ -187,6 +237,14 @@ def _normalize_data(data: TableData) -> JSONType:
vf = mo_data.csv(data)
return vf.url
+ # Handle polars
+ if DependencyManager.has_polars():
+ import polars as pl
+
+ if isinstance(data, pl.DataFrame):
+ vf = mo_data.csv(data)
+ return vf.url
+
# Assert that data is a list
if not isinstance(data, (list, tuple)):
raise ValueError("data must be a list or tuple.")
diff --git a/marimo/_plugins/ui/_impl/test_table.py b/marimo/_plugins/ui/_impl/test_table.py
index 15a22c6a35..6c85197752 100644
--- a/marimo/_plugins/ui/_impl/test_table.py
+++ b/marimo/_plugins/ui/_impl/test_table.py
@@ -41,7 +41,7 @@ def test_normalize_data() -> None:
{"key1": "value1"},
{"key2": "value2"},
{"key3": "value3"},
- ] # type: ignore
+ ]
result = _normalize_data(data)
assert result == [
{"key1": "value1"},
diff --git a/marimo/_plugins/ui/_impl/utils/dataframe.py b/marimo/_plugins/ui/_impl/utils/dataframe.py
index c8e29ff390..914c7326c7 100644
--- a/marimo/_plugins/ui/_impl/utils/dataframe.py
+++ b/marimo/_plugins/ui/_impl/utils/dataframe.py
@@ -4,7 +4,6 @@ from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
- Dict,
List,
Sequence,
Union,
@@ -13,6 +12,11 @@ from typing import (
from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.mime import MIME
+from marimo._plugins.core.web_component import JSONType
+
+if TYPE_CHECKING:
+ import pandas as pd
+ import polars as pl
LOGGER = _loggers.marimo_logger()
@@ -20,15 +24,13 @@ Numeric = Union[int, float]
TableData = Union[
Sequence[Union[str, int, float, bool, MIME, None]],
- Sequence[Dict[str, Union[str, int, float, bool, MIME, None]]],
+ Sequence[JSONType],
+ List[JSONType],
"pd.DataFrame",
+ "pl.DataFrame",
]
-if TYPE_CHECKING:
- import pandas as pd
-
-
def get_row_headers(
data: TableData,
) -> List[tuple[str, List[str | int | float]]]:
diff --git a/pyproject.toml b/pyproject.toml
index 983c7a28e0..e6a1eaa801 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -58,6 +58,7 @@ dev = [
# For testing mo.ui.chart
"pandas>=1.3.0",
"pandas-stubs>=1.3.0",
+ "polars>=0.19.12",
"pytest~=7.4.0",
"mypy~=1.4.1",
"ruff~=0.0.275",