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: polars support in `mo.ui.dataframe` transformations (#1612)

Myles Scolnickfdd5d8d3f0c1
diff --git a/frontend/src/components/datasets/icons.tsx b/frontend/src/components/datasets/icons.tsx
index 97eb55ca94..d5b04580b5 100644
--- a/frontend/src/components/datasets/icons.tsx
+++ b/frontend/src/components/datasets/icons.tsx
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { DataType } from "@/core/kernel/messages";
import {
ToggleLeftIcon,
CalendarIcon,
@@ -9,14 +10,6 @@ import {
type LucideIcon,
} from "lucide-react";
-export type DataType =
- | "string"
- | "boolean"
- | "integer"
- | "number"
- | "date"
- | "unknown";
-
/**
* Maps a data type to an icon.
*/
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index c81e3db765..79c0da6c49 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -10,9 +10,17 @@ import type { AppConfig } from "../config/config-schema";
import type { ColumnPreviewSummary } from "../datasets/types";
import type { JsonString } from "@/utils/json/base64";
+export type DataType =
+ | "string"
+ | "boolean"
+ | "integer"
+ | "number"
+ | "date"
+ | "unknown";
+
export interface DataTableColumn {
name: string;
- type: "string" | "boolean" | "integer" | "number" | "date" | "unknown";
+ type: DataType;
}
export interface DataTable {
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 90014d8c2e..3096592207 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -37,6 +37,7 @@ type PluginFunctions = {
has_more: boolean;
total_rows: number;
row_headers: Array<[string, string[]]>;
+ supports_code_sample: boolean;
}>;
get_column_values: (req: { column: string }) => Promise<{
values: unknown[];
@@ -70,6 +71,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")
has_more: z.boolean(),
total_rows: z.number(),
row_headers: z.array(z.tuple([z.string(), z.array(z.any())])),
+ supports_code_sample: z.boolean(),
}),
),
get_column_values: rpc.input(z.object({ column: z.string() })).output(
@@ -117,7 +119,8 @@ export const DataFrameComponent = memo(
() => get_dataframe({}),
[value?.transforms],
);
- const { url, has_more, total_rows, row_headers } = data || {};
+ const { url, has_more, total_rows, row_headers, supports_code_sample } =
+ data || {};
const [internalValue, setInternalValue] = useState<Transformations>(
value || EMPTY,
@@ -131,10 +134,12 @@ export const DataFrameComponent = memo(
<FunctionSquareIcon className="w-3 h-3 mr-2" />
Transform
</TabsTrigger>
- <TabsTrigger value="code" className="text-xs py-1">
- <Code2Icon className="w-3 h-3 mr-2" />
- Code
- </TabsTrigger>
+ {supports_code_sample && (
+ <TabsTrigger value="code" className="text-xs py-1">
+ <Code2Icon className="w-3 h-3 mr-2" />
+ Code
+ </TabsTrigger>
+ )}
</TabsList>
<TabsContent
value="transform"
@@ -152,12 +157,14 @@ export const DataFrameComponent = memo(
getColumnValues={get_column_values}
/>
</TabsContent>
- <TabsContent
- value="code"
- className="mt-1 border rounded-t overflow-hidden"
- >
- <CodePanel dataframeName={dataframeName} transforms={value} />
- </TabsContent>
+ {supports_code_sample && (
+ <TabsContent
+ value="code"
+ className="mt-1 border rounded-t overflow-hidden"
+ >
+ <CodePanel dataframeName={dataframeName} transforms={value} />
+ </TabsContent>
+ )}
</Tabs>
{error && <ErrorBanner error={error} />}
{has_more && total_rows != null && (
diff --git a/frontend/src/plugins/impl/data-frames/forms/datatype-icon.tsx b/frontend/src/plugins/impl/data-frames/forms/datatype-icon.tsx
index 4f8008bab5..1c592f55c7 100644
--- a/frontend/src/plugins/impl/data-frames/forms/datatype-icon.tsx
+++ b/frontend/src/plugins/impl/data-frames/forms/datatype-icon.tsx
@@ -18,11 +18,12 @@ export const DataTypeIcon: React.FC<Props> = ({ type }) => {
type.startsWith("int") ||
type.startsWith("float") ||
type.startsWith("uint") ||
+ type.startsWith("number") ||
type.startsWith("complex")
) {
return <BinaryIcon size={14} />;
}
- if (type.startsWith("object")) {
+ if (type.startsWith("object") || type.startsWith("string")) {
return <CaseSensitiveIcon size={14} />;
}
if (type.startsWith("date") || type.startsWith("time")) {
diff --git a/frontend/src/plugins/impl/data-frames/panel.tsx b/frontend/src/plugins/impl/data-frames/panel.tsx
index b698693945..d08a69ae0b 100644
--- a/frontend/src/plugins/impl/data-frames/panel.tsx
+++ b/frontend/src/plugins/impl/data-frames/panel.tsx
@@ -188,7 +188,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
onDelete,
}) => {
return (
- <div className="flex flex-col overflow-y-hidden w-[150px] shadow-xs h-full">
+ <div className="flex flex-col overflow-y-hidden w-[180px] shadow-xs h-full">
<div className="flex flex-col overflow-y-auto flex-grow">
{items.map((item, idx) => {
return (
diff --git a/frontend/src/plugins/impl/data-frames/types.ts b/frontend/src/plugins/impl/data-frames/types.ts
index 1208b48bcc..b9b54c1020 100644
--- a/frontend/src/plugins/impl/data-frames/types.ts
+++ b/frontend/src/plugins/impl/data-frames/types.ts
@@ -1,21 +1,26 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { DataType } from "@/core/kernel/messages";
+import { logNever } from "@/utils/assertNever";
+
/**
* Strongly typed string/number
*/
export type ColumnId = (string | number) & { __columnId: "columnId" };
+export type NumPyType = string;
+
/**
* List of column Id and their data types
*
* We cannot use a js map, since maps don't preserve keys as ints (e.g. "1" and 1 are the same key)
*/
-export type RawColumnDataTypes = Array<[ColumnId, string]>;
+export type RawColumnDataTypes = Array<[ColumnId, NumPyType]>;
/**
* Map of column Id and their data types
* ES6 maps preserve keys as ints (e.g. "1" and 1 are different keys)
*/
-export type ColumnDataTypes = Map<ColumnId, string>;
+export type ColumnDataTypes = Map<ColumnId, NumPyType>;
export const NUMPY_DTYPES = [
"int8",
@@ -41,6 +46,42 @@ export const NUMPY_DTYPES = [
"timedelta64",
] as const;
+export function numpyTypeToDataType(
+ nptype: (typeof NUMPY_DTYPES)[number],
+): DataType {
+ switch (nptype) {
+ case "int8":
+ case "int16":
+ case "int32":
+ case "int64":
+ case "uint8":
+ case "uint16":
+ case "uint32":
+ case "uint64":
+ return "integer";
+ case "float16":
+ case "float32":
+ case "float64":
+ case "float128":
+ return "number";
+ case "complex64":
+ case "complex128":
+ case "complex256":
+ case "object":
+ case "string_":
+ case "unicode_":
+ return "string";
+ case "bool":
+ return "boolean";
+ case "datetime64":
+ case "timedelta64":
+ return "date";
+ default:
+ logNever(nptype);
+ return "unknown";
+ }
+}
+
export const AGGREGATION_FNS = [
"count",
"sum",
diff --git a/marimo/_data/models.py b/marimo/_data/models.py
index 0d5f3db3bb..bb260c671b 100644
--- a/marimo/_data/models.py
+++ b/marimo/_data/models.py
@@ -7,6 +7,7 @@ from decimal import Decimal
from typing import List, Literal, Optional, Union
DataType = Literal["string", "boolean", "integer", "number", "date", "unknown"]
+NumpyType = str
@dataclass
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index dcb43aaaaf..41180399d5 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -3,8 +3,8 @@ from __future__ import annotations
import inspect
import sys
+from dataclasses import dataclass
from typing import (
- TYPE_CHECKING,
Any,
Callable,
Dict,
@@ -14,23 +14,22 @@ from typing import (
Union,
)
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._plugins.core.web_component import JSONType
-from marimo._plugins.ui._impl.dataframes.handlers import TransformsContainer
-from marimo._plugins.ui._impl.dataframes.transforms import Transformations
-from marimo._plugins.ui._impl.tables.pandas_table import (
- PandasTableManagerFactory,
-)
-from marimo._plugins.ui._impl.tables.table_manager import ColumnName
-
-if TYPE_CHECKING:
- import pandas as pd
-
-from dataclasses import dataclass
-
import marimo._output.data.data as mo_data
from marimo._output.rich_help import mddoc
+from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._impl.dataframes.transforms.apply import (
+ TransformsContainer,
+ get_handler_for_dataframe,
+)
+from marimo._plugins.ui._impl.dataframes.transforms.types import (
+ DataFrameType,
+ Transformations,
+)
+from marimo._plugins.ui._impl.tables.table_manager import ColumnName
+from marimo._plugins.ui._impl.tables.utils import (
+ get_table_manager,
+)
from marimo._runtime.functions import EmptyArgs, Function
from marimo._utils.parse_dataclass import parse_raw
@@ -41,6 +40,7 @@ class GetDataFrameResponse:
has_more: bool
total_rows: int
row_headers: List[tuple[str, List[str | int | float]]]
+ supports_code_sample: bool
@dataclass
@@ -73,14 +73,10 @@ class GetDataFrameError(Exception):
@mddoc
-class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
+class dataframe(UIElement[Dict[str, Any], DataFrameType]):
"""
Run transformations on a DataFrame or series.
- Currently only Pandas DataFrames are supported.
-
- For Polars DataFrames, you can convert to a Pandas DataFrame.
- However the returned DataFrame will still be a Pandas DataFrame,
- so you will need to convert back to a Polars DataFrame if you want.
+ Currently only Pandas or Polars DataFrames are supported.
**Example.**
@@ -88,10 +84,6 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
dataframe = mo.ui.dataframe(data)
```
- ```python
- dataframe = mo.ui.dataframe(polars_df.to_pandas())
- ```
-
**Attributes.**
- `value`: the transformed DataFrame or series
@@ -110,17 +102,12 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
def __init__(
self,
- df: pd.DataFrame,
- on_change: Optional[Callable[[pd.DataFrame], None]] = None,
+ df: DataFrameType,
+ on_change: Optional[Callable[[DataFrameType], None]] = None,
page_size: Optional[int] = 5,
) -> None:
- DependencyManager.require_pandas("to use the dataframe plugin")
- import pandas as pd
-
- if not isinstance(df, pd.DataFrame):
- raise ValueError(
- "Dataframe plugin only supports Pandas DataFrames"
- )
+ # This will raise an error if the dataframe type is not supported.
+ handler = get_handler_for_dataframe(df)
# HACK: this is a hack to get the name of the variable that was passed
dataframe_name = "df"
@@ -138,8 +125,11 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
pass
self._data = df
- self._manager = PandasTableManagerFactory.create()(df)
- self._transform_container = TransformsContainer(df)
+ self._handler = handler
+ self._manager = get_table_manager(df)
+ self._transform_container = TransformsContainer[DataFrameType](
+ df, handler
+ )
self._error: Optional[str] = None
super().__init__(
@@ -152,7 +142,7 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
args={
"columns": self._get_column_types(),
"dataframe-name": dataframe_name,
- "total": len(df),
+ "total": self._manager.get_num_rows(),
"page-size": page_size,
},
functions=(
@@ -175,22 +165,24 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
)
def _get_column_types(self) -> List[List[Union[str, int]]]:
- return [[name, dtype] for name, dtype in self._data.dtypes.items()] # type: ignore
+ return [
+ [name, dtype]
+ for name, dtype in self._manager.get_field_types().items()
+ ]
def get_dataframe(self, _args: EmptyArgs) -> GetDataFrameResponse:
if self._error is not None:
raise GetDataFrameError(self._error)
- manager = PandasTableManagerFactory.create()(
- self._value.head(self.DISPLAY_LIMIT)
- )
+ manager = get_table_manager(self._value).limit(self.DISPLAY_LIMIT)
url = mo_data.csv(manager.to_csv()).url
- total_rows = len(self._value)
+ total_rows = manager.get_num_rows(force=True) or self.DISPLAY_LIMIT
return GetDataFrameResponse(
url=url,
total_rows=total_rows,
has_more=total_rows > self.DISPLAY_LIMIT,
row_headers=manager.get_row_headers(),
+ supports_code_sample=self._handler.supports_code_sample(),
)
def get_column_values(
@@ -199,12 +191,13 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
"""Get all the unique values in a column."""
LIMIT = 500
- if args.column not in self._data.columns:
+ columns = self._manager.get_column_names()
+ if args.column not in columns:
raise ColumnNotFound(args.column)
# We get the unique values from the original dataframe, not the
# transformed one
- unique_values = self._data[args.column].unique().tolist()
+ unique_values = self._manager.get_unique_column_values(args.column)
if len(unique_values) <= LIMIT:
return GetColumnValuesResponse(
values=list(sorted(unique_values, key=str)),
@@ -216,7 +209,7 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
too_many_values=True,
)
- def _convert_value(self, value: Dict[str, Any]) -> pd.DataFrame:
+ def _convert_value(self, value: Dict[str, Any]) -> DataFrameType:
if value is None:
self._error = None
return self._data
diff --git a/marimo/_plugins/ui/_impl/dataframes/handlers.py b/marimo/_plugins/ui/_impl/dataframes/handlers.py
deleted file mode 100644
index 7344e7a392..0000000000
--- a/marimo/_plugins/ui/_impl/dataframes/handlers.py
+++ /dev/null
@@ -1,294 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-from __future__ import annotations
-
-from typing import TYPE_CHECKING, Any, List, NoReturn, cast
-
-from marimo._plugins.ui._impl.dataframes.transforms import (
- AggregateTransform,
- ColumnConversionTransform,
- FilterRowsTransform,
- GroupByTransform,
- RenameColumnTransform,
- SampleRowsTransform,
- SelectColumnsTransform,
- ShuffleRowsTransform,
- SortColumnTransform,
- Transform,
- Transformations,
- TransformType,
-)
-
-if TYPE_CHECKING:
- import pandas as pd
-
-
-class TransformHandlers:
- @staticmethod
- def handle(df: "pd.DataFrame", transform: Transform) -> "pd.DataFrame":
- transform_type: TransformType = transform.type
-
- if transform_type is TransformType.COLUMN_CONVERSION:
- return TransformHandlers.handle_column_conversion(
- df, cast(ColumnConversionTransform, transform)
- )
- elif transform_type is TransformType.RENAME_COLUMN:
- return TransformHandlers.handle_rename_column(
- df, cast(RenameColumnTransform, transform)
- )
- elif transform_type is TransformType.SORT_COLUMN:
- return TransformHandlers.handle_sort_column(
- df, cast(SortColumnTransform, transform)
- )
- elif transform_type is TransformType.FILTER_ROWS:
- return TransformHandlers.handle_filter_rows(
- df, cast(FilterRowsTransform, transform)
- )
- elif transform_type is TransformType.GROUP_BY:
- return TransformHandlers.handle_group_by(
- df, cast(GroupByTransform, transform)
- )
- elif transform_type is TransformType.AGGREGATE:
- return TransformHandlers.handle_aggregate(
- df, cast(AggregateTransform, transform)
- )
- elif transform_type is TransformType.SELECT_COLUMNS:
- return TransformHandlers.handle_select_columns(
- df, cast(SelectColumnsTransform, transform)
- )
- elif transform_type is TransformType.SHUFFLE_ROWS:
- return TransformHandlers.handle_shuffle_rows(
- df, cast(ShuffleRowsTransform, transform)
- )
- elif transform_type is TransformType.SAMPLE_ROWS:
- return TransformHandlers.handle_sample_rows(
- df, cast(SampleRowsTransform, transform)
- )
-
- else:
- _assert_never(transform_type)
-
- @staticmethod
- def handle_column_conversion(
- df: "pd.DataFrame", transform: ColumnConversionTransform
- ) -> "pd.DataFrame":
- df[transform.column_id] = df[transform.column_id].astype(
- transform.data_type,
- errors=transform.errors,
- ) # type: ignore[call-overload]
- return df
-
- @staticmethod
- def handle_rename_column(
- df: "pd.DataFrame", transform: RenameColumnTransform
- ) -> "pd.DataFrame":
- return df.rename(
- columns={transform.column_id: transform.new_column_id}
- )
-
- @staticmethod
- def handle_sort_column(
- df: "pd.DataFrame", transform: SortColumnTransform
- ) -> "pd.DataFrame":
- return df.sort_values(
- by=cast(str, transform.column_id),
- ascending=transform.ascending,
- na_position=transform.na_position,
- )
-
- @staticmethod
- def handle_filter_rows(
- df: "pd.DataFrame", transform: FilterRowsTransform
- ) -> "pd.DataFrame":
- for condition in transform.where:
- value = _coerce_value(
- df[condition.column_id].dtype, condition.value
- )
- if condition.operator == "==":
- df_filter = df[condition.column_id] == value
- elif condition.operator == "!=":
- df_filter = df[condition.column_id] != value
- elif condition.operator == ">":
- df_filter = df[condition.column_id] > value
- elif condition.operator == "<":
- df_filter = df[condition.column_id] < value
- elif condition.operator == ">=":
- df_filter = df[condition.column_id] >= value
- elif condition.operator == "<=":
- df_filter = df[condition.column_id] <= value
- elif condition.operator == "is_true":
- df_filter = df[condition.column_id].eq(True)
- elif condition.operator == "is_false":
- df_filter = df[condition.column_id].eq(False)
- elif condition.operator == "is_nan":
- df_filter = df[condition.column_id].isna()
- elif condition.operator == "is_not_nan":
- df_filter = df[condition.column_id].notna()
- elif condition.operator == "equals":
- df_filter = df[condition.column_id].eq(value)
- elif condition.operator == "does_not_equal":
- df_filter = df[condition.column_id].ne(value)
- elif condition.operator == "contains":
- df_filter = df[condition.column_id].str.contains(
- value, regex=False
- )
- elif condition.operator == "regex":
- df_filter = df[condition.column_id].str.contains(
- value, regex=True
- )
- elif condition.operator == "starts_with":
- df_filter = df[condition.column_id].str.startswith(value)
- elif condition.operator == "ends_with":
- df_filter = df[condition.column_id].str.endswith(value)
- elif condition.operator == "in":
- df_filter = df[condition.column_id].isin(value)
- else:
- _assert_never(condition.operator)
-
- if transform.operation == "keep_rows":
- df = df[df_filter]
- elif transform.operation == "remove_rows":
- df = df[~df_filter]
- else:
- _assert_never(transform.operation)
- return df
-
- @staticmethod
- def handle_group_by(
- df: "pd.DataFrame", transform: GroupByTransform
- ) -> "pd.DataFrame":
- group = df.groupby(transform.column_ids, dropna=transform.drop_na)
- if transform.aggregation == "count":
- return group.count()
- elif transform.aggregation == "sum":
- return group.sum()
- elif transform.aggregation == "mean":
- return group.mean(numeric_only=True)
- elif transform.aggregation == "median":
- return group.median(numeric_only=True)
- elif transform.aggregation == "min":
- return group.min()
- elif transform.aggregation == "max":
- return group.max()
- else:
- _assert_never(transform.aggregation)
-
- @staticmethod
- def handle_aggregate(
- df: "pd.DataFrame", transform: AggregateTransform
- ) -> "pd.DataFrame":
- dict_of_aggs = {
- column_id: transform.aggregations
- for column_id in transform.column_ids
- }
-
- # Pandas type-checking doesn't like the fact that the values
- # are lists of strings (function names), even though the docs permit
- # such a value
- return cast("pd.DataFrame", df.agg(dict_of_aggs)) # type: ignore # noqa: E501
-
- @staticmethod
- def handle_select_columns(
- df: "pd.DataFrame", transform: SelectColumnsTransform
- ) -> "pd.DataFrame":
- return df[transform.column_ids]
-
- @staticmethod
- def handle_shuffle_rows(
- df: "pd.DataFrame", transform: ShuffleRowsTransform
- ) -> "pd.DataFrame":
- return df.sample(frac=1, random_state=transform.seed)
-
- @staticmethod
- def handle_sample_rows(
- df: "pd.DataFrame", transform: SampleRowsTransform
- ) -> "pd.DataFrame":
- return df.sample(
- n=transform.n,
- random_state=transform.seed,
- replace=transform.replace,
- )
-
-
-def apply_transforms(
- df: "pd.DataFrame", transforms: Transformations
-) -> "pd.DataFrame":
- if not transforms.transforms:
- return df
- for transform in transforms.transforms:
- df = TransformHandlers.handle(df, transform)
- return df
-
-
-def _assert_never(value: NoReturn) -> NoReturn:
- raise AssertionError(f"Unhandled value: {value} ({type(value).__name__})")
-
-
-def _coerce_value(dtype: Any, value: Any) -> Any:
- import numpy as np
-
- return np.array([value]).astype(dtype)[0]
-
-
-class TransformsContainer:
- """
- Keeps internal state of the last transformation applied to the dataframe.
- So that we can incrementally apply transformations.
- """
-
- def __init__(self, df: "pd.DataFrame") -> None:
- self._original_df = df
- # The dataframe for the given transform.
- self._snapshot_df = df
- self._transforms: List[Transform] = []
-
- def apply(self, transform: Transformations) -> "pd.DataFrame":
- """
- Applies the given transformations to the dataframe.
- """
- # If the new transformations are a superset of the existing ones,
- # then we can just apply the new ones to the snapshot dataframe.
- if self._is_superset(transform):
- transforms_to_apply = self._get_next_transformations(transform)
- self._snapshot_df = apply_transforms(
- self._snapshot_df, transforms_to_apply
- )
- self._transforms = transform.transforms
- return self._snapshot_df
-
- # If the new transformations are not a superset of the existing ones,
- # then we need to start from the original dataframe.
- else:
- self._snapshot_df = apply_transforms(self._original_df, transform)
- self._transforms = transform.transforms
- return self._snapshot_df
-
- def _is_superset(self, transforms: Transformations) -> bool:
- """
- Checks if the new transformations are a superset of the existing ones.
- """
- if not self._transforms:
- return False
-
- # If the new transformations are smaller than the existing ones,
- # then it's not a superset.
- if len(self._transforms) > len(transforms.transforms):
- return False
-
- for i, transform in enumerate(self._transforms):
- if transform != transforms.transforms[i]:
- return False
-
- return True
-
- def _get_next_transformations(
- self, transforms: Transformations
- ) -> Transformations:
- """
- Gets the next transformations to apply.
- """
- if self._is_superset(transforms):
- return Transformations(
- transforms.transforms[len(self._transforms) :]
- )
- else:
- return transforms
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py b/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py
new file mode 100644
index 0000000000..e37aff4365
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py
@@ -0,0 +1,142 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any, Generic, List, TypeVar
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.ui._impl.dataframes.transforms.handlers import (
+ PandasTransformHandler,
+ PolarsTransformHandler,
+)
+from marimo._plugins.ui._impl.dataframes.transforms.types import (
+ Transform,
+ Transformations,
+ TransformHandler,
+ TransformType,
+)
+from marimo._utils.assert_never import assert_never
+
+T = TypeVar("T")
+
+
+def handle(df: T, handler: TransformHandler[T], transform: Transform) -> T:
+ if transform.type is TransformType.COLUMN_CONVERSION:
+ return handler.handle_column_conversion(df, transform)
+ elif transform.type is TransformType.RENAME_COLUMN:
+ return handler.handle_rename_column(df, transform)
+ elif transform.type is TransformType.SORT_COLUMN:
+ return handler.handle_sort_column(df, transform)
+ elif transform.type is TransformType.FILTER_ROWS:
+ return handler.handle_filter_rows(df, transform)
+ elif transform.type is TransformType.GROUP_BY:
+ return handler.handle_group_by(df, transform)
+ elif transform.type is TransformType.AGGREGATE:
+ return handler.handle_aggregate(df, transform)
+ elif transform.type is TransformType.SELECT_COLUMNS:
+ return handler.handle_select_columns(df, transform)
+ elif transform.type is TransformType.SHUFFLE_ROWS:
+ return handler.handle_shuffle_rows(df, transform)
+ elif transform.type is TransformType.SAMPLE_ROWS:
+ return handler.handle_sample_rows(df, transform)
+ else:
+ assert_never(transform.type)
+
+
+def apply_transforms(
+ df: T, handler: TransformHandler[T], transforms: Transformations
+) -> T:
+ if not transforms.transforms:
+ return df
+ for transform in transforms.transforms:
+ df = handle(df, handler, transform)
+ return df
+
+
+def get_handler_for_dataframe(
+ df: Any,
+) -> TransformHandler[Any]:
+ """
+ Gets the handler for the given dataframe.
+
+ raises ValueError if the dataframe type is not supported.
+ """
+ if DependencyManager.has_pandas():
+ import pandas as pd
+
+ if isinstance(df, pd.DataFrame):
+ return PandasTransformHandler()
+ if DependencyManager.has_polars():
+ import polars as pl
+
+ if isinstance(df, pl.DataFrame):
+ return PolarsTransformHandler()
+
+ raise ValueError("Unsupported dataframe type. Must be Pandas or Polars.")
+
+
+class TransformsContainer(Generic[T]):
+ """
+ Keeps internal state of the last transformation applied to the dataframe.
+ So that we can incrementally apply transformations.
+ """
+
+ def __init__(self, df: T, handler: TransformHandler[T]) -> None:
+ self._original_df = df
+ # The dataframe for the given transform.
+ self._snapshot_df = df
+ self._handler = handler
+ self._transforms: List[Transform] = []
+
+ def apply(self, transform: Transformations) -> T:
+ """
+ Applies the given transformations to the dataframe.
+ """
+ # If the new transformations are a superset of the existing ones,
+ # then we can just apply the new ones to the snapshot dataframe.
+ if self._is_superset(transform):
+ transforms_to_apply = self._get_next_transformations(transform)
+ self._snapshot_df = apply_transforms(
+ self._snapshot_df, self._handler, transforms_to_apply
+ )
+ self._transforms = transform.transforms
+ return self._snapshot_df
+
+ # If the new transformations are not a superset of the existing ones,
+ # then we need to start from the original dataframe.
+ else:
+ self._snapshot_df = apply_transforms(
+ self._original_df, self._handler, transform
+ )
+ self._transforms = transform.transforms
+ return self._snapshot_df
+
+ def _is_superset(self, transforms: Transformations) -> bool:
+ """
+ Checks if the new transformations are a superset of the existing ones.
+ """
+ if not self._transforms:
+ return False
+
+ # If the new transformations are smaller than the existing ones,
+ # then it's not a superset.
+ if len(self._transforms) > len(transforms.transforms):
+ return False
+
+ for i, transform in enumerate(self._transforms):
+ if transform != transforms.transforms[i]:
+ return False
+
+ return True
+
+ def _get_next_transformations(
+ self, transforms: Transformations
+ ) -> Transformations:
+ """
+ Gets the next transformations to apply.
+ """
+ if self._is_superset(transforms):
+ return Transformations(
+ transforms.transforms[len(self._transforms) :]
+ )
+ else:
+ return transforms
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
new file mode 100644
index 0000000000..ff2662a894
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
@@ -0,0 +1,379 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Optional, cast
+
+from marimo._plugins.ui._impl.dataframes.transforms.types import (
+ AggregateTransform,
+ ColumnConversionTransform,
+ FilterRowsTransform,
+ GroupByTransform,
+ RenameColumnTransform,
+ SampleRowsTransform,
+ SelectColumnsTransform,
+ ShuffleRowsTransform,
+ SortColumnTransform,
+ TransformHandler,
+)
+from marimo._utils.assert_never import assert_never
+
+if TYPE_CHECKING:
+ import pandas as pd
+ import polars as pl
+
+
+class PandasTransformHandler(TransformHandler["pd.DataFrame"]):
+ @staticmethod
+ def supports_code_sample() -> bool:
+ return True
+
+ @staticmethod
+ def handle_column_conversion(
+ df: "pd.DataFrame", transform: ColumnConversionTransform
+ ) -> "pd.DataFrame":
+ df[transform.column_id] = df[transform.column_id].astype(
+ transform.data_type,
+ errors=transform.errors,
+ ) # type: ignore[call-overload]
+ return df
+
+ @staticmethod
+ def handle_rename_column(
+ df: "pd.DataFrame", transform: RenameColumnTransform
+ ) -> "pd.DataFrame":
+ return df.rename(
+ columns={transform.column_id: transform.new_column_id}
+ )
+
+ @staticmethod
+ def handle_sort_column(
+ df: "pd.DataFrame", transform: SortColumnTransform
+ ) -> "pd.DataFrame":
+ return df.sort_values(
+ by=cast(str, transform.column_id),
+ ascending=transform.ascending,
+ na_position=transform.na_position,
+ )
+
+ @staticmethod
+ def handle_filter_rows(
+ df: "pd.DataFrame", transform: FilterRowsTransform
+ ) -> "pd.DataFrame":
+ for condition in transform.where:
+ value = _coerce_value(
+ df[condition.column_id].dtype, condition.value
+ )
+ if condition.operator == "==":
+ df_filter = df[condition.column_id] == value
+ elif condition.operator == "!=":
+ df_filter = df[condition.column_id] != value
+ elif condition.operator == ">":
+ df_filter = df[condition.column_id] > value
+ elif condition.operator == "<":
+ df_filter = df[condition.column_id] < value
+ elif condition.operator == ">=":
+ df_filter = df[condition.column_id] >= value
+ elif condition.operator == "<=":
+ df_filter = df[condition.column_id] <= value
+ elif condition.operator == "is_true":
+ df_filter = df[condition.column_id].eq(True)
+ elif condition.operator == "is_false":
+ df_filter = df[condition.column_id].eq(False)
+ elif condition.operator == "is_nan":
+ df_filter = df[condition.column_id].isna()
+ elif condition.operator == "is_not_nan":
+ df_filter = df[condition.column_id].notna()
+ elif condition.operator == "equals":
+ df_filter = df[condition.column_id].eq(value)
+ elif condition.operator == "does_not_equal":
+ df_filter = df[condition.column_id].ne(value)
+ elif condition.operator == "contains":
+ df_filter = df[condition.column_id].str.contains(
+ value, regex=False
+ )
+ elif condition.operator == "regex":
+ df_filter = df[condition.column_id].str.contains(
+ value, regex=True
+ )
+ elif condition.operator == "starts_with":
+ df_filter = df[condition.column_id].str.startswith(value)
+ elif condition.operator == "ends_with":
+ df_filter = df[condition.column_id].str.endswith(value)
+ elif condition.operator == "in":
+ df_filter = df[condition.column_id].isin(value)
+ else:
+ assert_never(condition.operator)
+
+ if transform.operation == "keep_rows":
+ df = df[df_filter]
+ elif transform.operation == "remove_rows":
+ df = df[~df_filter]
+ else:
+ assert_never(transform.operation)
+ return df
+
+ @staticmethod
+ def handle_group_by(
+ df: "pd.DataFrame", transform: GroupByTransform
+ ) -> "pd.DataFrame":
+ group = df.groupby(transform.column_ids, dropna=transform.drop_na)
+ if transform.aggregation == "count":
+ return group.count()
+ elif transform.aggregation == "sum":
+ return group.sum()
+ elif transform.aggregation == "mean":
+ return group.mean(numeric_only=True)
+ elif transform.aggregation == "median":
+ return group.median(numeric_only=True)
+ elif transform.aggregation == "min":
+ return group.min()
+ elif transform.aggregation == "max":
+ return group.max()
+ else:
+ assert_never(transform.aggregation)
+
+ @staticmethod
+ def handle_aggregate(
+ df: "pd.DataFrame", transform: AggregateTransform
+ ) -> "pd.DataFrame":
+ dict_of_aggs = {
+ column_id: transform.aggregations
+ for column_id in transform.column_ids
+ }
+
+ # Pandas type-checking doesn't like the fact that the values
+ # are lists of strings (function names), even though the docs permit
+ # such a value
+ return cast("pd.DataFrame", df.agg(dict_of_aggs)) # type: ignore # noqa: E501
+
+ @staticmethod
+ def handle_select_columns(
+ df: "pd.DataFrame", transform: SelectColumnsTransform
+ ) -> "pd.DataFrame":
+ return df[transform.column_ids]
+
+ @staticmethod
+ def handle_shuffle_rows(
+ df: "pd.DataFrame", transform: ShuffleRowsTransform
+ ) -> "pd.DataFrame":
+ return df.sample(frac=1, random_state=transform.seed)
+
+ @staticmethod
+ def handle_sample_rows(
+ df: "pd.DataFrame", transform: SampleRowsTransform
+ ) -> "pd.DataFrame":
+ return df.sample(
+ n=transform.n,
+ random_state=transform.seed,
+ replace=transform.replace,
+ )
+
+
+class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):
+ @staticmethod
+ def supports_code_sample() -> bool:
+ return False
+
+ @staticmethod
+ def handle_column_conversion(
+ df: "pl.DataFrame", transform: ColumnConversionTransform
+ ) -> "pl.DataFrame":
+ import polars.datatypes as pl_datatypes
+
+ def numpy_type_to_polars_type(dtype: str) -> pl.PolarsDataType:
+ polars_dtype = pl_datatypes.numpy_char_code_to_dtype(dtype)
+ return polars_dtype
+
+ return df.cast(
+ {
+ str(transform.column_id): numpy_type_to_polars_type(
+ transform.data_type
+ )
+ },
+ strict=transform.errors == "raise",
+ )
+
+ @staticmethod
+ def handle_rename_column(
+ df: "pl.DataFrame", transform: RenameColumnTransform
+ ) -> "pl.DataFrame":
+ return df.rename(
+ {str(transform.column_id): str(transform.new_column_id)}
+ )
+
+ @staticmethod
+ def handle_sort_column(
+ df: "pl.DataFrame", transform: SortColumnTransform
+ ) -> "pl.DataFrame":
+ return df.sort(
+ by=transform.column_id,
+ descending=not transform.ascending,
+ nulls_last=transform.na_position == "last",
+ )
+
+ @staticmethod
+ def handle_filter_rows(
+ df: "pl.DataFrame", transform: FilterRowsTransform
+ ) -> "pl.DataFrame":
+ from polars import col
+
+ # Start with no filter (all rows included)
+ filter_expr: Optional[pl.Expr] = None
+
+ # Iterate over all conditions and build the filter expression
+ for condition in transform.where:
+ column = col(str(condition.column_id))
+ value = condition.value
+
+ # Build the expression based on the operator
+ if condition.operator == "==":
+ condition_expr = column == value
+ elif condition.operator == "!=":
+ condition_expr = column != value
+ elif condition.operator == ">":
+ condition_expr = column > value
+ elif condition.operator == "<":
+ condition_expr = column < value
+ elif condition.operator == ">=":
+ condition_expr = column >= value
+ elif condition.operator == "<=":
+ condition_expr = column <= value
+ elif condition.operator == "is_true":
+ condition_expr = column.eq(True)
+ elif condition.operator == "is_false":
+ condition_expr = column.eq(False)
+ elif condition.operator == "is_nan":
+ condition_expr = column.is_null()
+ elif condition.operator == "is_not_nan":
+ condition_expr = column.is_not_null()
+ elif condition.operator == "equals":
+ condition_expr = column == value
+ elif condition.operator == "does_not_equal":
+ condition_expr = column != value
+ elif condition.operator == "contains":
+ condition_expr = column.str.contains(value or "", literal=True)
+ elif condition.operator == "regex":
+ condition_expr = column.str.contains(
+ value or "", literal=False
+ )
+ elif condition.operator == "starts_with":
+ condition_expr = column.str.starts_with(value or "")
+ elif condition.operator == "ends_with":
+ condition_expr = column.str.ends_with(value or "")
+ elif condition.operator == "in":
+ condition_expr = column.is_in(value or [])
+ else:
+ assert_never(condition.operator)
+
+ # Combine the condition expression with the filter expression
+ if filter_expr is None:
+ filter_expr = condition_expr
+ else:
+ filter_expr = filter_expr & condition_expr
+
+ if filter_expr is None:
+ return df
+
+ # Handle the operation (keep_rows or remove_rows)
+ if transform.operation == "keep_rows":
+ return df.filter(filter_expr)
+ elif transform.operation == "remove_rows":
+ return df.filter(~filter_expr)
+ else:
+ assert_never(transform.operation)
+
+ @staticmethod
+ def handle_group_by(
+ df: "pl.DataFrame", transform: GroupByTransform
+ ) -> "pl.DataFrame":
+ aggs: list[pl.Expr] = []
+ from polars import col
+
+ group_by_column_id_set = set(transform.column_ids)
+ agg_columns = [
+ column_id
+ for column_id in df.columns
+ if column_id not in group_by_column_id_set
+ ]
+ for column_id in agg_columns:
+ agg_func = transform.aggregation
+ if agg_func == "count":
+ aggs.append(col(column_id).count().alias(f"{column_id}_count"))
+ elif agg_func == "sum":
+ aggs.append(col(column_id).sum().alias(f"{column_id}_sum"))
+ elif agg_func == "mean":
+ aggs.append(col(column_id).mean().alias(f"{column_id}_mean"))
+ elif agg_func == "median":
+ aggs.append(
+ col(column_id).median().alias(f"{column_id}_median")
+ )
+ elif agg_func == "min":
+ aggs.append(col(column_id).min().alias(f"{column_id}_min"))
+ elif agg_func == "max":
+ aggs.append(col(column_id).max().alias(f"{column_id}_max"))
+ else:
+ assert_never(agg_func)
+
+ return df.group_by(transform.column_ids, maintain_order=True).agg(aggs)
+
+ @staticmethod
+ def handle_aggregate(
+ df: "pl.DataFrame", transform: AggregateTransform
+ ) -> "pl.DataFrame":
+ import polars as pl
+
+ selected_df = df.select(transform.column_ids)
+ result_df = pl.DataFrame()
+ for agg_func in transform.aggregations:
+ if agg_func == "count":
+ agg_df = selected_df.count()
+ elif agg_func == "sum":
+ agg_df = selected_df.sum()
+ elif agg_func == "mean":
+ agg_df = selected_df.mean()
+ elif agg_func == "median":
+ agg_df = selected_df.median()
+ elif agg_func == "min":
+ agg_df = selected_df.min()
+ elif agg_func == "max":
+ agg_df = selected_df.max()
+ else:
+ assert_never(agg_func)
+
+ # Rename all
+ agg_df = agg_df.rename(
+ {column: f"{column}_{agg_func}" for column in agg_df.columns}
+ )
+ # Add to result
+ result_df = result_df.hstack(agg_df)
+
+ return result_df
+
+ @staticmethod
+ def handle_select_columns(
+ df: "pl.DataFrame", transform: SelectColumnsTransform
+ ) -> "pl.DataFrame":
+ return df.select(transform.column_ids)
+
+ @staticmethod
+ def handle_shuffle_rows(
+ df: "pl.DataFrame", transform: ShuffleRowsTransform
+ ) -> "pl.DataFrame":
+ return df.sample(fraction=1, shuffle=True, seed=transform.seed)
+
+ @staticmethod
+ def handle_sample_rows(
+ df: "pl.DataFrame", transform: SampleRowsTransform
+ ) -> "pl.DataFrame":
+ return df.sample(
+ n=transform.n,
+ shuffle=True,
+ seed=transform.seed,
+ with_replacement=transform.replace,
+ )
+
+
+def _coerce_value(dtype: Any, value: Any) -> Any:
+ import numpy as np
+
+ return np.array([value]).astype(dtype)[0]
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms.py b/marimo/_plugins/ui/_impl/dataframes/transforms/types.py
similarity index 59%
rename from marimo/_plugins/ui/_impl/dataframes/transforms.py
rename to marimo/_plugins/ui/_impl/dataframes/transforms/types.py
index 819fcb9cdc..3c40449874 100644
--- a/marimo/_plugins/ui/_impl/dataframes/transforms.py
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/types.py
@@ -1,9 +1,21 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import abc
from dataclasses import dataclass
from enum import Enum
-from typing import Any, List, Literal, Optional, Union
+from typing import (
+ Any,
+ Generic,
+ List,
+ Literal,
+ Optional,
+ TypeVar,
+ Union,
+)
+
+# Could be a DataFrame from pandas, polars, pyarrow, DataFrameProtocol, etc.
+DataFrameType = TypeVar("DataFrameType")
ColumnId = Union[str, int]
ColumnIds = List[ColumnId]
@@ -138,3 +150,60 @@ Transform = Union[
@dataclass
class Transformations:
transforms: List[Transform]
+
+
+T = TypeVar("T")
+
+
+class TransformHandler(abc.ABC, Generic[T]):
+ @staticmethod
+ @abc.abstractmethod
+ def supports_code_sample() -> bool:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_column_conversion(
+ df: T, transform: ColumnConversionTransform
+ ) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_rename_column(df: T, transform: RenameColumnTransform) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_sort_column(df: T, transform: SortColumnTransform) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_filter_rows(df: T, transform: FilterRowsTransform) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_group_by(df: T, transform: GroupByTransform) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_aggregate(df: T, transform: AggregateTransform) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_select_columns(df: T, transform: SelectColumnsTransform) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_shuffle_rows(df: T, transform: ShuffleRowsTransform) -> T:
+ raise NotImplementedError
+
+ @staticmethod
+ @abc.abstractmethod
+ def handle_sample_rows(df: T, transform: SampleRowsTransform) -> T:
+ raise NotImplementedError
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index e93c006fb7..32b9d718be 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -144,6 +144,11 @@ class DefaultTableManager(TableManager[JsonTableData]):
return list(first.keys())
return ["value"]
+ def get_unique_column_values(self, column: str) -> list[str | int | float]:
+ return sorted(
+ self._as_table_manager().get_unique_column_values(column)
+ )
+
def sort_values(
self, by: ColumnName, descending: bool
) -> DefaultTableManager:
diff --git a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
index 7dafef57ff..8435e0f13c 100644
--- a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
+++ b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py
@@ -104,6 +104,11 @@ class DataFrameProtocolTableManager(TableManager[DataFrameLike]):
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]:
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 97d50a5f5a..46cf606f4b 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -226,6 +226,11 @@ class PandasTableManagerFactory(TableManagerFactory):
def get_column_names(self) -> list[str]:
return self.data.columns.tolist()
+ def get_unique_column_values(
+ self, column: str
+ ) -> list[str | int | float]:
+ return self.data[column].unique().tolist() # type: ignore[no-any-return]
+
def sort_values(
self, by: ColumnName, descending: bool
) -> PandasTableManager:
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index a11bb1a774..868d451071 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -120,6 +120,11 @@ class PolarsTableManagerFactory(TableManagerFactory):
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
) -> PolarsTableManager:
diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
index 81c5fd9c51..5a88fdcdcf 100644
--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
@@ -155,6 +155,13 @@ class PyArrowTableManagerFactory(TableManagerFactory):
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:
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 78a976a004..b5f155e7c3 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -5,7 +5,7 @@ import abc
from typing import Any, Dict, Generic, Optional, TypeVar
import marimo._output.data.data as mo_data
-from marimo._data.models import ColumnSummary, DataType
+from marimo._data.models import ColumnSummary, DataType, NumpyType
from marimo._plugins.core.web_component import JSONType
T = TypeVar("T")
@@ -13,6 +13,7 @@ T = TypeVar("T")
ColumnName = str
FieldType = DataType
FieldTypes = Dict[ColumnName, FieldType]
+NumpyTypes = Dict[ColumnName, NumpyType]
class TableManager(abc.ABC, Generic[T]):
@@ -98,6 +99,10 @@ class TableManager(abc.ABC, Generic[T]):
def get_column_names(self) -> list[str]:
raise NotImplementedError
+ @abc.abstractmethod
+ def get_unique_column_values(self, column: str) -> list[str | int | float]:
+ raise NotImplementedError
+
class TableManagerFactory(abc.ABC):
@staticmethod
diff --git a/marimo/_smoke_tests/dataframe.py b/marimo/_smoke_tests/dataframe.py
index b7db31f929..f791e1527d 100644
--- a/marimo/_smoke_tests/dataframe.py
+++ b/marimo/_smoke_tests/dataframe.py
@@ -2,7 +2,7 @@
import marimo
-__generated_with = "0.6.12"
+__generated_with = "0.6.18"
app = marimo.App(width="full")
@@ -128,6 +128,25 @@ def __(mo):
return
+def __(mo):
+ mo.md("## mo.ui.dataframe")
+ return
+
+
+def __(mo, pl_dataframe):
+ pl_dataframe_prime = mo.ui.dataframe(pl_dataframe)
+ pl_dataframe_prime
+ return pl_dataframe_prime,
+
+
+def __(pl_dataframe_prime):
+ pl_dataframe_prime.value
+ return
+
+
@app.cell(hide_code=True)
def __(mo):
mo.md("## mo.ui.table")
@@ -209,11 +228,13 @@ def __(mo):
@app.cell
-def __(dask_dfda):
+def __():
import dask.dataframe as dd
- dask_df = dd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
- dask_dfda
+ dask_df = dd.read_csv(
+ "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
+ )
+ dask_df
return dask_df, dd
@@ -223,7 +244,10 @@ def __():
ibis.options.interactive = True
- ibis_data = ibis.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv", table_name="penguins")
+ ibis_data = ibis.read_csv(
+ "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv",
+ table_name="penguins",
+ )
ibis_data
return ibis, ibis_data
diff --git a/marimo/_utils/assert_never.py b/marimo/_utils/assert_never.py
new file mode 100644
index 0000000000..569e5b0506
--- /dev/null
+++ b/marimo/_utils/assert_never.py
@@ -0,0 +1,8 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import NoReturn
+
+
+def assert_never(value: NoReturn) -> NoReturn:
+ raise AssertionError(f"Unhandled value: {value} ({type(value).__name__})")
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
index 750c464cf6..81b6d4ea00 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -1,5 +1,8 @@
from __future__ import annotations
+from typing import Any
+from unittest.mock import Mock
+
import pytest
from marimo._dependencies.dependencies import DependencyManager
@@ -10,52 +13,73 @@ from marimo._plugins.ui._impl.dataframes.dataframe import (
GetColumnValuesResponse,
)
-HAS_DEPS = DependencyManager.has_pandas()
+HAS_DEPS = (
+ DependencyManager.has_pandas()
+ and DependencyManager.has_numpy()
+ and DependencyManager.has_polars()
+)
if HAS_DEPS:
- import numpy as np
import pandas as pd
+ import polars as pl
+else:
+ pd = Mock()
+ pl = Mock()
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
-def test_dataframe() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]})
-
- subject = ui.dataframe(df)
+class TestDataframes:
+ @staticmethod
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pd.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]}),
+ pl.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]}),
+ ],
+ )
+ def test_dataframe(
+ df: Any,
+ ) -> None:
+ subject = ui.dataframe(df)
- assert subject.value is df
- assert subject._component_args["columns"] == [
- ["A", np.dtype("int64")],
- ["B", np.dtype("O")],
- ]
- assert subject.get_column_values(
- GetColumnValuesArgs(column="A")
- ) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)
- assert subject.get_column_values(
- GetColumnValuesArgs(column="B")
- ) == GetColumnValuesResponse(values=["a"], too_many_values=False)
+ assert subject.value is df
+ assert subject._component_args["columns"] == [
+ ["A", "integer"],
+ ["B", "string"],
+ ]
+ assert subject.get_column_values(
+ GetColumnValuesArgs(column="A")
+ ) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)
+ assert subject.get_column_values(
+ GetColumnValuesArgs(column="B")
+ ) == GetColumnValuesResponse(values=["a"], too_many_values=False)
- with pytest.raises(ColumnNotFound):
- subject.get_column_values(GetColumnValuesArgs(column="idk"))
-
-
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-def test_dataframe_numeric_columns() -> None:
- df = pd.DataFrame({1: [1, 2, 3], 2: ["a", "a", "a"]})
+ with pytest.raises(ColumnNotFound):
+ subject.get_column_values(GetColumnValuesArgs(column="idk"))
- subject = ui.dataframe(df)
+ @staticmethod
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pd.DataFrame({1: [1, 2, 3], 2: ["a", "a", "a"]}),
+ ],
+ )
+ def test_dataframe_numeric_columns(
+ df: Any,
+ ) -> None:
+ subject = ui.dataframe(df)
- assert subject.value is df
- assert subject._component_args["columns"] == [
- [1, np.dtype("int64")],
- [2, np.dtype("O")],
- ]
+ assert subject.value is df
+ assert subject._component_args["columns"] == [
+ [1, "integer"],
+ [2, "string"],
+ ]
- assert subject.get_column_values(
- GetColumnValuesArgs(column=1)
- ) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)
+ assert subject.get_column_values(
+ GetColumnValuesArgs(column=1)
+ ) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)
- with pytest.raises(ColumnNotFound):
- subject.get_column_values(GetColumnValuesArgs(column="idk"))
- with pytest.raises(ColumnNotFound):
- subject.get_column_values(GetColumnValuesArgs(column="1"))
+ with pytest.raises(ColumnNotFound):
+ subject.get_column_values(GetColumnValuesArgs(column="idk"))
+ with pytest.raises(ColumnNotFound):
+ subject.get_column_values(GetColumnValuesArgs(column="1"))
diff --git a/tests/_plugins/ui/_impl/dataframes/test_handlers.py b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
index 53fcbf739b..ae49833e2d 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_handlers.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
@@ -1,17 +1,21 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from unittest.mock import Mock
+
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._plugins.ui._impl.dataframes.handlers import (
+from marimo._plugins.ui._impl.dataframes.transforms.apply import (
TransformsContainer,
apply_transforms,
+ get_handler_for_dataframe,
)
-from marimo._plugins.ui._impl.dataframes.transforms import (
+from marimo._plugins.ui._impl.dataframes.transforms.types import (
AggregateTransform,
ColumnConversionTransform,
Condition,
+ DataFrameType,
FilterRowsTransform,
GroupByTransform,
RenameColumnTransform,
@@ -24,162 +28,346 @@ from marimo._plugins.ui._impl.dataframes.transforms import (
TransformType,
)
-HAS_DEPS = DependencyManager.has_pandas()
+HAS_DEPS = DependencyManager.has_pandas() and DependencyManager.has_polars()
if HAS_DEPS:
import pandas as pd
+ import polars as pl
+ import polars.testing as pl_testing
+else:
+ pd = Mock()
+ pl = Mock()
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-class TestHandlers:
- @staticmethod
- def apply(df: "pd.DataFrame", transform: Transform) -> "pd.DataFrame":
- return apply_transforms(df, Transformations(transforms=[transform]))
+def apply(df: DataFrameType, transform: Transform) -> DataFrameType:
+ handler = get_handler_for_dataframe(df)
+ return apply_transforms(
+ df, handler, Transformations(transforms=[transform])
+ )
+
+
+def assert_frame_equal(df1: DataFrameType, df2: DataFrameType) -> None:
+ if isinstance(df1, pd.DataFrame) and isinstance(df2, pd.DataFrame):
+ # Remove index to compare
+ df1 = df1.reset_index(drop=True)
+ df2 = df2.reset_index(drop=True)
+ pd.testing.assert_frame_equal(df1, df2)
+ return
+ if isinstance(df1, pl.DataFrame) and isinstance(df2, pl.DataFrame):
+ pl_testing.assert_frame_equal(df1, df2)
+ return
+ pytest.fail("DataFrames are not of the same type")
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+class TestPandasHandler:
@staticmethod
- def test_handle_column_conversion() -> None:
- # 1 string to int
- df = pd.DataFrame({"A": ["1", "2", "3"]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": ["1", "2", "3"]}),
+ pd.DataFrame({"A": [1, 2, 3]}),
+ ),
+ (
+ pl.DataFrame({"A": ["1", "2", "3"]}),
+ pl.DataFrame({"A": [1, 2, 3]}),
+ ),
+ ],
+ )
+ def test_handle_column_conversion_string_to_int(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = ColumnConversionTransform(
type=TransformType.COLUMN_CONVERSION,
column_id="A",
- data_type="int",
+ data_type="int64",
errors="raise",
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].dtype == "int"
- # 2 float to string
- df = pd.DataFrame({"A": [1.1, 2.2, 3.3]})
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1.1, 2.2, 3.3]}),
+ pd.DataFrame({"A": ["1.1", "2.2", "3.3"]}),
+ ),
+ (
+ pl.DataFrame({"A": [1.1, 2.2, 3.3]}),
+ pl.DataFrame({"A": ["1.1", "2.2", "3.3"]}),
+ ),
+ ],
+ )
+ def test_handle_column_conversion_float_to_string(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = ColumnConversionTransform(
type=TransformType.COLUMN_CONVERSION,
column_id="A",
data_type="str",
errors="raise",
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].dtype == "object"
- assert result["A"].tolist() == ["1.1", "2.2", "3.3"]
- # 3 with errors
- df = pd.DataFrame({"A": ["1", "2", "3", "a"]})
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": ["1", "2", "3", "a"]}),
+ pd.DataFrame({"A": ["1", "2", "3", "a"]}),
+ ),
+ (
+ pl.DataFrame({"A": ["1", "2", "3", "a"]}),
+ pl.DataFrame({"A": [1, 2, 3, None]}),
+ ),
+ ],
+ )
+ def test_handle_column_conversion_ignore_errors(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = ColumnConversionTransform(
type=TransformType.COLUMN_CONVERSION,
column_id="A",
- data_type="int",
+ data_type="int64",
errors="ignore",
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].dtype == "object"
- assert result["A"].tolist() == ["1", "2", "3", "a"]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_rename_column() -> None:
- df = pd.DataFrame({"A": [1, 2, 3]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3]}),
+ pd.DataFrame({"B": [1, 2, 3]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3]}),
+ pl.DataFrame({"B": [1, 2, 3]}),
+ ),
+ ],
+ )
+ def test_handle_rename_column(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = RenameColumnTransform(
type=TransformType.RENAME_COLUMN, column_id="A", new_column_id="B"
)
- result = TestHandlers.apply(df, transform)
- assert "B" in result.columns
- assert "A" not in result.columns
-
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
- transform = RenameColumnTransform(
- type=TransformType.RENAME_COLUMN, column_id="B", new_column_id="C"
- )
- result = TestHandlers.apply(df, transform)
- assert "C" in result.columns
- assert "B" not in result.columns
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_sort_column() -> None:
- df = pd.DataFrame({"A": [3, 2, 1]})
+ @pytest.mark.parametrize(
+ ("df", "expected_asc", "expected_desc"),
+ [
+ (
+ pd.DataFrame({"A": [3, 1, 2]}),
+ pd.DataFrame({"A": [1, 2, 3]}),
+ pd.DataFrame({"A": [3, 2, 1]}),
+ ),
+ (
+ pl.DataFrame({"A": [3, 1, 2]}),
+ pl.DataFrame({"A": [1, 2, 3]}),
+ pl.DataFrame({"A": [3, 2, 1]}),
+ ),
+ ],
+ )
+ def test_handle_sort_column(
+ df: DataFrameType,
+ expected_asc: DataFrameType,
+ expected_desc: DataFrameType,
+ ) -> None:
transform = SortColumnTransform(
type=TransformType.SORT_COLUMN,
column_id="A",
ascending=True,
na_position="last",
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [1, 2, 3]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected_asc)
- df = pd.DataFrame({"A": [3, 2, 1], "B": [1, 3, 2]})
transform = SortColumnTransform(
type=TransformType.SORT_COLUMN,
- column_id="B",
+ column_id="A",
ascending=False,
na_position="last",
)
- result = TestHandlers.apply(df, transform)
- assert result["B"].tolist() == [3, 2, 1]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected_desc)
@staticmethod
- def test_handle_filter_rows_1() -> None:
- df = pd.DataFrame({"A": [1, 2, 3]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3]}),
+ pd.DataFrame({"A": [2, 3]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3]}),
+ pl.DataFrame({"A": [2, 3]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_1(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="keep_rows",
where=[Condition(column_id="A", operator=">=", value=2)],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [2, 3]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_2() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [2], "B": [5]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [2], "B": [5]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_2(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="remove_rows",
where=[Condition(column_id="B", operator="!=", value=5)],
)
- result = TestHandlers.apply(df, transform)
- assert result["B"].tolist() == [5]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_3() -> None:
- df = pd.DataFrame({"A": [1, 2, 3, 4, 5]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3, 4, 5]}),
+ pd.DataFrame({"A": [1, 2, 3]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3, 4, 5]}),
+ pl.DataFrame({"A": [1, 2, 3]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_3(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="keep_rows",
where=[Condition(column_id="A", operator="<", value=4)],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [1, 2, 3]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_4() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3]}),
+ pd.DataFrame({"A": [1, 3]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3]}),
+ pl.DataFrame({"A": [1, 3]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_4(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="remove_rows",
where=[Condition(column_id="A", operator="==", value=2)],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [1, 3]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_5() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [2, 3], "B": [5, 6]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [2, 3], "B": [5, 6]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_5(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="keep_rows",
where=[Condition(column_id="B", operator=">=", value=5)],
)
- result = TestHandlers.apply(df, transform)
- assert result["B"].tolist() == [5, 6]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_6() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [3], "B": [6]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [3], "B": [6]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_6(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="remove_rows",
where=[Condition(column_id="B", operator="<", value=6)],
)
- result = TestHandlers.apply(df, transform)
- assert result["B"].tolist() == [6]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_multiple_conditions_1() -> None:
- df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]}),
+ pd.DataFrame({"A": [3, 4, 5], "B": [3, 2, 1]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]}),
+ pl.DataFrame({"A": [3, 4, 5], "B": [3, 2, 1]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_multiple_conditions_1(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="keep_rows",
@@ -188,13 +376,26 @@ class TestHandlers:
Condition(column_id="B", operator="<=", value=3),
],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [3, 4, 5]
- assert result["B"].tolist() == [3, 2, 1]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_multiple_conditions_2() -> None:
- df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]}),
+ pd.DataFrame({"A": [1, 3, 4, 5], "B": [5, 3, 2, 1]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]}),
+ pl.DataFrame({"A": [1, 3, 4, 5], "B": [5, 3, 2, 1]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_multiple_conditions_2(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="remove_rows",
@@ -203,161 +404,305 @@ class TestHandlers:
Condition(column_id="B", operator="==", value=4),
],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [1, 3, 4, 5]
- assert result["B"].tolist() == [5, 3, 2, 1]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_boolean() -> None:
- df = pd.DataFrame({"A": [True, False, True, False]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [True, False, True, False]}),
+ pd.DataFrame({"A": [True, True]}),
+ ),
+ (
+ pl.DataFrame({"A": [True, False, True, False]}),
+ pl.DataFrame({"A": [True, True]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_boolean(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="keep_rows",
where=[Condition(column_id="A", operator="is_true")],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [True, True]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
- df = pd.DataFrame({"A": [True, False, True, False]})
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="remove_rows",
where=[Condition(column_id="A", operator="is_false")],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"].tolist() == [True, True]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_filter_rows_unknown_column() -> None:
- df = pd.DataFrame({"A": [1, 2, 3]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3]}),
+ KeyError,
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3]}),
+ pl.exceptions.ColumnNotFoundError,
+ ),
+ ],
+ )
+ def test_handle_filter_rows_unknown_column(
+ df: DataFrameType, expected: Exception
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="keep_rows",
where=[Condition(column_id="B", operator=">=", value=2)],
)
- with pytest.raises(KeyError):
- TestHandlers.apply(df, transform)
+ with pytest.raises(expected):
+ apply(df, transform)
@staticmethod
- def test_handle_filter_rows_number_columns() -> None:
- df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]}),
+ pd.DataFrame({1: [2, 3], 2: [5, 6]}),
+ ),
+ (
+ pl.DataFrame({"1": [1, 2, 3], "2": [4, 5, 6]}),
+ pl.DataFrame({"1": [2, 3], "2": [5, 6]}),
+ ),
+ ],
+ )
+ def test_handle_filter_rows_number_columns(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="keep_rows",
where=[Condition(column_id=1, operator=">=", value=2)],
)
- result = TestHandlers.apply(df, transform)
- assert result[1].tolist() == [2, 3]
- assert result[2].tolist() == [5, 6]
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_group_by() -> None:
- df = pd.DataFrame({"A": ["foo", "foo", "bar"], "B": [1, 2, 3]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": ["foo", "foo", "bar"], "B": [1, 2, 3]}),
+ pd.DataFrame({"B": [3, 3]}),
+ ),
+ (
+ pd.DataFrame(
+ {"A": ["foo", "foo", "bar", "bar"], "B": [1, 2, 3, 4]}
+ ),
+ pd.DataFrame({"B": [7, 3]}),
+ ),
+ (
+ pl.DataFrame({"A": ["foo", "foo", "bar"], "B": [1, 2, 4]}),
+ pl.DataFrame({"A": ["foo", "bar"], "B_sum": [3, 4]}),
+ ),
+ ],
+ )
+ def test_handle_group_by(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = GroupByTransform(
type=TransformType.GROUP_BY,
column_ids=["A"],
drop_na=False,
aggregation="sum",
)
- result = TestHandlers.apply(df, transform)
- assert result["B"].tolist() == [3, 3]
-
- df = pd.DataFrame(
- {"A": ["foo", "foo", "bar", "bar"], "B": [1, 2, 3, 4]}
- )
- transform = GroupByTransform(
- type=TransformType.GROUP_BY,
- column_ids=["A"],
- drop_na=False,
- aggregation="mean",
- )
- result = TestHandlers.apply(df, transform)
- assert set(result["B"].tolist()) == set([1.5, 3.5])
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_aggregate() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [6], "B": [15]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame(
+ {
+ "A_sum": [6],
+ "B_sum": [15],
+ }
+ ),
+ ),
+ ],
+ )
+ def test_handle_aggregate_sum(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = AggregateTransform(
type=TransformType.AGGREGATE,
column_ids=["A", "B"],
aggregations=["sum"],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"]["sum"] == 6
- assert result["B"]["sum"] == 15
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @staticmethod
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [1, 3], "B": [4, 6]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame(
+ {
+ "A_min": [1],
+ "B_min": [4],
+ "A_max": [3],
+ "B_max": [6],
+ }
+ ),
+ ),
+ ],
+ )
+ def test_handle_aggregate_min_max(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = AggregateTransform(
type=TransformType.AGGREGATE,
column_ids=["A", "B"],
aggregations=["min", "max"],
)
- result = TestHandlers.apply(df, transform)
- assert result["A"]["min"] == 1
- assert result["A"]["max"] == 3
- assert result["B"]["min"] == 4
- assert result["B"]["max"] == 6
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_handle_select_columns() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [1, 2, 3]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [1, 2, 3]}),
+ ),
+ ],
+ )
+ def test_handle_select_columns_single(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = SelectColumnsTransform(
type=TransformType.SELECT_COLUMNS, column_ids=["A"]
)
- result = TestHandlers.apply(df, transform)
- assert "A" in result.columns
- assert "B" not in result.columns
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
- transform = SelectColumnsTransform(
- type=TransformType.SELECT_COLUMNS, column_ids=["B"]
- )
- result = TestHandlers.apply(df, transform)
- assert "B" in result.columns
- assert "A" not in result.columns
-
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @staticmethod
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ ),
+ ],
+ )
+ def test_handle_select_columns_multiple(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
transform = SelectColumnsTransform(
type=TransformType.SELECT_COLUMNS, column_ids=["A", "B"]
)
- result = TestHandlers.apply(df, transform)
- assert "A" in result.columns
- assert "B" in result.columns
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
@staticmethod
- def test_shuffle_rows() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [2, 3, 1], "B": [5, 6, 4]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [2, 3, 1], "B": [5, 6, 4]}),
+ ),
+ ],
+ )
+ def test_shuffle_rows(df: DataFrameType, expected: DataFrameType) -> None:
transform = ShuffleRowsTransform(
type=TransformType.SHUFFLE_ROWS, seed=42
)
- result = TestHandlers.apply(df, transform)
- assert len(result) == 3
+ result = apply(df, transform)
+ assert len(result) == len(expected)
assert "A" in result.columns
assert "B" in result.columns
@staticmethod
- def test_sample_rows() -> None:
- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [1, 3], "B": [4, 6]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [1, 3], "B": [4, 6]}),
+ ),
+ ],
+ )
+ def test_sample_rows(df: DataFrameType, expected: DataFrameType) -> None:
transform = SampleRowsTransform(
type=TransformType.SAMPLE_ROWS, n=2, seed=42, replace=False
)
- result = TestHandlers.apply(df, transform)
- assert len(result) == 2
+ result = apply(df, transform)
+ assert len(result) == len(expected)
assert "A" in result.columns
assert "B" in result.columns
@staticmethod
- def test_transforms_container() -> None:
- # Create a sample dataframe
- df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})
+ @pytest.mark.parametrize(
+ ("df", "expected", "expected2"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 6, 5]}),
+ pd.DataFrame({"A": [3, 2], "B": [5, 6]}),
+ pd.DataFrame({"A": [2], "B": [6]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 6, 5]}),
+ pl.DataFrame({"A": [3, 2], "B": [5, 6]}),
+ pl.DataFrame({"A": [2], "B": [6]}),
+ ),
+ ],
+ )
+ def test_transforms_container(
+ df: DataFrameType, expected: DataFrameType, expected2: DataFrameType
+ ) -> None:
# Create a TransformsContainer object
- container = TransformsContainer(df)
+ container = TransformsContainer(df, get_handler_for_dataframe(df))
# Define some transformations
sort_transform = SortColumnTransform(
type=TransformType.SORT_COLUMN,
column_id="B",
- ascending=False,
+ ascending=True,
na_position="last",
)
filter_transform = FilterRowsTransform(
@@ -378,14 +723,13 @@ class TestHandlers:
# Get the transformed dataframe
# Check that the transformations were applied correctly
- assert result["A"].tolist() == [2, 3, 4, 5]
- assert result["B"].tolist() == [4, 3, 2, 1]
+ assert_frame_equal(result, expected)
# Reapply transforms by adding a new one
filter_again_transform = FilterRowsTransform(
type=TransformType.FILTER_ROWS,
operation="remove_rows",
- where=[Condition(column_id="B", operator="==", value=4)],
+ where=[Condition(column_id="B", operator="==", value=5)],
)
transformations = Transformations(
[sort_transform, filter_transform, filter_again_transform]
@@ -399,8 +743,7 @@ class TestHandlers:
transformations,
)
# Check that the transformations were applied correctly
- assert result["A"].tolist() == [3, 4, 5]
- assert result["B"].tolist() == [3, 2, 1]
+ assert_frame_equal(result, expected2)
transformations = Transformations([sort_transform, filter_transform])
# Verify the next transformation
@@ -414,5 +757,4 @@ class TestHandlers:
transformations,
)
# Check that the transformations were applied correctly
- assert result["A"].tolist() == [2, 3, 4, 5]
- assert result["B"].tolist() == [4, 3, 2, 1]
+ assert_frame_equal(result, expected)
diff --git a/tests/_plugins/ui/_impl/dataframes/test_transforms.py b/tests/_plugins/ui/_impl/dataframes/test_transforms.py
index a0413bc602..9543ba060e 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_transforms.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_transforms.py
@@ -1,5 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
-from marimo._plugins.ui._impl.dataframes.transforms import Transformations
+from __future__ import annotations
+
+from marimo._plugins.ui._impl.dataframes.transforms.types import (
+ Transformations,
+)
from marimo._utils.parse_dataclass import parse_raw
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index c88daf3610..a2ce17b002 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -4,8 +4,13 @@ import unittest
from datetime import date
from typing import Any, Dict
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.default_table import DefaultTableManager
+HAS_DEPS = DependencyManager.has_pandas()
+
class TestDefaultTable(unittest.TestCase):
def setUp(self) -> None:
@@ -186,3 +191,10 @@ class TestColumnarDefaultTable(unittest.TestCase):
{"name": "Alice", "age": 30, "birth_year": date(1994, 5, 24)},
]
assert sorted_data == expected_data
+
+ @pytest.mark.skipif(
+ not HAS_DEPS, reason="optional dependencies not installed"
+ )
+ def test_get_unique_column_values(self) -> None:
+ unique_values = self.manager.get_unique_column_values("age")
+ assert unique_values == [22, 25, 28, 30, 35]
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 1c733e2da1..914d4c3255 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -338,3 +338,7 @@ class TestPandasTableManager(unittest.TestCase):
sorted_df = self.manager.sort_values("A", descending=True).data
expected_df = self.data.sort_values("A", ascending=False)
assert sorted_df.equals(expected_df)
+
+ def test_get_unique_column_values(self) -> None:
+ column = "B"
+ assert self.manager.get_unique_column_values(column) == ["a", "b", "c"]
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 77d11eb3f9..29357f13e2 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -204,3 +204,8 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
sorted_df = self.manager.sort_values("A", descending=True).data
expected_df = self.data.sort("A", descending=True)
assert sorted_df.equals(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]
diff --git a/tests/_plugins/ui/_impl/tables/test_pyarrow.py b/tests/_plugins/ui/_impl/tables/test_pyarrow.py
index 47a1c5eccd..899089a98f 100644
--- a/tests/_plugins/ui/_impl/tables/test_pyarrow.py
+++ b/tests/_plugins/ui/_impl/tables/test_pyarrow.py
@@ -167,3 +167,8 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):
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 == ["a", "b", "c"]
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 09cac912e0..473bc48313 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -98,7 +98,7 @@ def test_normalize_data(executing_kernel: Kernel) -> None:
)
-def test_sort_1d_list_of_strings(dtm):
+def test_sort_1d_list_of_strings(dtm: DefaultTableManager):
data = ["banana", "apple", "cherry", "date", "elderberry"]
dtm.data = _normalize_data(data)
sorted_data = dtm.sort_values(by="value", descending=False).data
@@ -112,7 +112,7 @@ def test_sort_1d_list_of_strings(dtm):
assert sorted_data == expected_data
-def test_sort_1d_list_of_integers(dtm):
+def test_sort_1d_list_of_integers(dtm: DefaultTableManager):
data = [42, 17, 23, 99, 8]
dtm.data = _normalize_data(data)
sorted_data = dtm.sort_values(by="value", descending=False).data
@@ -126,7 +126,7 @@ def test_sort_1d_list_of_integers(dtm):
assert sorted_data == expected_data
-def test_sort_list_of_dicts(dtm):
+def test_sort_list_of_dicts(dtm: DefaultTableManager):
data = [
{"name": "Alice", "age": 30, "birth_year": date(1994, 5, 24)},
{"name": "Bob", "age": 25, "birth_year": date(1999, 7, 14)},
@@ -137,8 +137,8 @@ def test_sort_list_of_dicts(dtm):
dtm.data = _normalize_data(data)
sorted_data = dtm.sort_values(by="age", descending=True).data
- with pytest.raises(Exception):
- dtm.sort_values(by="missing_column", descending=True).data
+ with pytest.raises(KeyError):
+ _res = dtm.sort_values(by="missing_column", descending=True).data
expected_data = [
{"name": "Charlie", "age": 35, "birth_year": date(1989, 12, 1)},
@@ -150,7 +150,7 @@ def test_sort_list_of_dicts(dtm):
assert sorted_data == expected_data
-def test_sort_dict_of_lists(dtm):
+def test_sort_dict_of_lists(dtm: DefaultTableManager):
data = {
"company": [
"Company A",
@@ -165,8 +165,8 @@ def test_sort_dict_of_lists(dtm):
dtm.data = _normalize_data(data)
sorted_data = dtm.sort_values(by="net_worth", descending=False).data
- with pytest.raises(Exception):
- dtm.sort_values(by="missing_column", descending=True).data
+ with pytest.raises(KeyError):
+ _res = dtm.sort_values(by="missing_column", descending=True).data
expected_data = {
"company": [
@@ -182,7 +182,7 @@ def test_sort_dict_of_lists(dtm):
assert sorted_data == _normalize_data(expected_data)
-def test_sort_dict_of_tuples(dtm):
+def test_sort_dict_of_tuples(dtm: DefaultTableManager):
data = {
"key1": (42, 17, 23),
"key2": (99, 8, 4),
@@ -193,8 +193,8 @@ def test_sort_dict_of_tuples(dtm):
dtm.data = _normalize_data(data)
sorted_data = dtm.sort_values(by="key1", descending=True).data
- with pytest.raises(Exception):
- dtm.sort_values(by="missing_column", descending=True).data
+ with pytest.raises(KeyError):
+ _res = dtm.sort_values(by="missing_column", descending=True).data
expected_data = [
{"key1": 42, "key2": 99, "key3": 34, "key4": 1, "key5": 7},