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: Add new data frame transformations for shuffl and sample (#363)

Myles Scolnick8ffd7d84d442
diff --git a/frontend/src/plugins/impl/data-frames/forms/form.tsx b/frontend/src/plugins/impl/data-frames/forms/form.tsx
index b02b45cf10..29e64697f2 100644
--- a/frontend/src/plugins/impl/data-frames/forms/form.tsx
+++ b/frontend/src/plugins/impl/data-frames/forms/form.tsx
@@ -26,8 +26,11 @@ import {
import { Objects } from "../../../../utils/objects";
import { Button } from "../../../../components/ui/button";
import { getDefaults, getUnionLiteral } from "./form-utils";
-import { PlusIcon, Trash2Icon } from "lucide-react";
-import { FieldOptions } from "@/plugins/impl/data-frames/forms/options";
+import { PlusIcon, RefreshCcw, Trash2Icon } from "lucide-react";
+import {
+ FieldOptions,
+ randomNumber,
+} from "@/plugins/impl/data-frames/forms/options";
import { cn } from "@/utils/cn";
import React, { useContext, useEffect } from "react";
import {
@@ -162,6 +165,27 @@ function renderZodSchema<T extends FieldValues, S>(
/>
);
} else if (schema instanceof z.ZodNumber) {
+ if (special === "random_number_button") {
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
+ <Button
+ size="xs"
+ variant="secondary"
+ onClick={() => {
+ field.onChange(randomNumber());
+ }}
+ >
+ <RefreshCcw className="w-3.5 h-3.5 mr-1" />
+ {label}
+ </Button>
+ )}
+ />
+ );
+ }
+
return (
<FormField
control={form.control}
diff --git a/frontend/src/plugins/impl/data-frames/forms/options.ts b/frontend/src/plugins/impl/data-frames/forms/options.ts
index 3f9532f2e0..92b591ffc3 100644
--- a/frontend/src/plugins/impl/data-frames/forms/options.ts
+++ b/frontend/src/plugins/impl/data-frames/forms/options.ts
@@ -8,6 +8,7 @@ export interface FieldOptions {
direction?: "row" | "column";
special?:
| "column_id"
+ | "random_number_button"
| "column_type"
| "radio_group"
| "column_filter"
@@ -33,3 +34,8 @@ export const FieldOptions = {
}
},
};
+
+// Random number between 0 and 100_000
+export function randomNumber(): number {
+ return Math.floor(Math.random() * 100_000);
+}
diff --git a/frontend/src/plugins/impl/data-frames/panel.tsx b/frontend/src/plugins/impl/data-frames/panel.tsx
index 5918b1c8d0..0f0eb50fdd 100644
--- a/frontend/src/plugins/impl/data-frames/panel.tsx
+++ b/frontend/src/plugins/impl/data-frames/panel.tsx
@@ -24,6 +24,7 @@ import { getDefaults, getUnionLiteral } from "./forms/form-utils";
import {
ArrowUpDownIcon,
ColumnsIcon,
+ CombineIcon,
FilterIcon,
FunctionSquareIcon,
GroupIcon,
@@ -31,6 +32,7 @@ import {
MousePointerSquareIcon,
PencilIcon,
PlusIcon,
+ ShuffleIcon,
Trash2Icon,
} from "lucide-react";
import { cn } from "../../../utils/cn";
@@ -283,4 +285,6 @@ const ICONS: Record<TransformType["type"], React.FC<{ className?: string }>> = {
rename_column: PencilIcon,
select_columns: MousePointerSquareIcon,
sort_column: ArrowUpDownIcon,
+ shuffle_rows: ShuffleIcon,
+ sample_rows: CombineIcon,
};
diff --git a/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts b/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts
index ab19dd557c..73ecaf59b0 100644
--- a/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts
+++ b/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts
@@ -128,6 +128,28 @@ it("generates correct Python code for select_columns", () => {
);
});
+// Test for sample_rows
+it("generates correct Python code for sample_rows", () => {
+ const transform: TransformType = {
+ type: "sample_rows",
+ n: 42,
+ seed: 10,
+ replace: false,
+ };
+ const result = pythonPrint("df", transform);
+ expect(result).toMatchInlineSnapshot('"df.sample(n=42)"');
+});
+
+// Test for shuffle_rows
+it("generates correct Python code for shuffle_rows", () => {
+ const transform: TransformType = {
+ type: "shuffle_rows",
+ seed: 10,
+ };
+ const result = pythonPrint("df", transform);
+ expect(result).toMatchInlineSnapshot('"df.sample(frac=1)"');
+});
+
describe("pythonPrint: filter", () => {
it("handles filter vs keep", () => {
const result = pythonPrint("df", {
diff --git a/frontend/src/plugins/impl/data-frames/python/python-print.ts b/frontend/src/plugins/impl/data-frames/python/python-print.ts
index b9325be5d1..b99ba70200 100644
--- a/frontend/src/plugins/impl/data-frames/python/python-print.ts
+++ b/frontend/src/plugins/impl/data-frames/python/python-print.ts
@@ -82,6 +82,12 @@ export function pythonPrint(dfName: string, transform: TransformType): string {
}
return `${dfName}[${listOfStrings(column_ids)}]`;
}
+ case "sample_rows": {
+ const { n } = transform;
+ return `${dfName}.sample(n=${n})`;
+ }
+ case "shuffle_rows":
+ return `${dfName}.sample(frac=1)`;
default:
logNever(transform);
diff --git a/frontend/src/plugins/impl/data-frames/schema.ts b/frontend/src/plugins/impl/data-frames/schema.ts
index a08c5fd0fc..d0ecb9e3a6 100644
--- a/frontend/src/plugins/impl/data-frames/schema.ts
+++ b/frontend/src/plugins/impl/data-frames/schema.ts
@@ -3,7 +3,10 @@ import {
AGGREGATION_FNS,
NUMPY_DTYPES,
} from "@/plugins/impl/data-frames/types";
-import { FieldOptions } from "@/plugins/impl/data-frames/forms/options";
+import {
+ FieldOptions,
+ randomNumber,
+} from "@/plugins/impl/data-frames/forms/options";
import { z } from "zod";
import {
ALL_OPERATORS,
@@ -123,6 +126,38 @@ const SelectColumnsTransformSchema = z.object({
column_ids: column_id_array,
});
+const SampleRowsTransformSchema = z.object({
+ type: z.literal("sample_rows"),
+ n: z
+ .number()
+ .positive()
+ .describe(FieldOptions.of({ label: "Number of rows" })),
+ seed: z
+ .number()
+ .default(() => randomNumber())
+ .describe(
+ FieldOptions.of({ label: "Re-sample", special: "random_number_button" })
+ ),
+ replace: z
+ .boolean()
+ .default(false)
+ .describe(
+ FieldOptions.of({
+ label: "Sample with replacement",
+ })
+ ),
+});
+
+const ShuffleRowsTransformSchema = z.object({
+ type: z.literal("shuffle_rows"),
+ seed: z
+ .number()
+ .default(() => randomNumber())
+ .describe(
+ FieldOptions.of({ label: "Re-shuffle", special: "random_number_button" })
+ ),
+});
+
export const TransformTypeSchema = z.union([
FilterRowsTransformSchema,
SelectColumnsTransformSchema,
@@ -131,6 +166,8 @@ export const TransformTypeSchema = z.union([
SortColumnTransformSchema,
GroupByTransformSchema,
AggregateTransformSchema,
+ SampleRowsTransformSchema,
+ ShuffleRowsTransformSchema,
]);
export type TransformType = z.infer<typeof TransformTypeSchema>;
diff --git a/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts
index 94427e252d..91e554a679 100644
--- a/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts
+++ b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts
@@ -56,13 +56,15 @@ function handleTransform(
return Objects.filter(next, (_v, k) =>
transform.column_ids.includes(k as string)
);
- case "filter_rows":
- case "sort_column":
- return next;
case "select_columns":
return Objects.filter(next, (_v, k) =>
transform.column_ids.includes(k as string)
);
+ case "filter_rows":
+ case "shuffle_rows":
+ case "sample_rows":
+ case "sort_column":
+ return next;
default:
logNever(transform);
return next;
diff --git a/marimo/_plugins/ui/_impl/dataframes/handlers.py b/marimo/_plugins/ui/_impl/dataframes/handlers.py
index c98155e4f8..ab291f3dfb 100644
--- a/marimo/_plugins/ui/_impl/dataframes/handlers.py
+++ b/marimo/_plugins/ui/_impl/dataframes/handlers.py
@@ -7,7 +7,9 @@ from .transforms import (
FilterRowsTransform,
GroupByTransform,
RenameColumnTransform,
+ SampleRowsTransform,
SelectColumnsTransform,
+ ShuffleRowsTransform,
SortColumnTransform,
Transform,
Transformations,
@@ -51,6 +53,14 @@ class TransformHandlers:
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)
@@ -176,6 +186,22 @@ class TransformHandlers:
) -> "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
diff --git a/marimo/_plugins/ui/_impl/dataframes/test_handlers.py b/marimo/_plugins/ui/_impl/dataframes/test_handlers.py
index 652459bc59..63fe780dc2 100644
--- a/marimo/_plugins/ui/_impl/dataframes/test_handlers.py
+++ b/marimo/_plugins/ui/_impl/dataframes/test_handlers.py
@@ -12,7 +12,9 @@ from marimo._plugins.ui._impl.dataframes.transforms import (
FilterRowsTransform,
GroupByTransform,
RenameColumnTransform,
+ SampleRowsTransform,
SelectColumnsTransform,
+ ShuffleRowsTransform,
SortColumnTransform,
Transform,
Transformations,
@@ -287,6 +289,26 @@ def test_handle_select_columns() -> None:
assert "B" in result.columns
+def test_shuffle_rows() -> None:
+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ transform = ShuffleRowsTransform(type=TransformType.SHUFFLE_ROWS, seed=42)
+ result = apply(df, transform)
+ assert len(result) == 3
+ assert "A" in result.columns
+ assert "B" in result.columns
+
+
+def test_sample_rows() -> None:
+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ transform = SampleRowsTransform(
+ type=TransformType.SAMPLE_ROWS, n=2, seed=42, replace=False
+ )
+ result = apply(df, transform)
+ assert len(result) == 2
+ assert "A" in result.columns
+ assert "B" in result.columns
+
+
def test_transforms_container() -> None:
# Create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms.py b/marimo/_plugins/ui/_impl/dataframes/transforms.py
index 887f11f82c..805a828604 100644
--- a/marimo/_plugins/ui/_impl/dataframes/transforms.py
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms.py
@@ -46,6 +46,8 @@ class TransformType(Enum):
RENAME_COLUMN = "rename_column"
SELECT_COLUMNS = "select_columns"
SORT_COLUMN = "sort_column"
+ SHUFFLE_ROWS = "shuffle_rows"
+ SAMPLE_ROWS = "sample_rows"
@dataclass
@@ -106,6 +108,20 @@ class SelectColumnsTransform:
column_ids: ColumnIds
+@dataclass
+class ShuffleRowsTransform:
+ type: Literal[TransformType.SHUFFLE_ROWS]
+ seed: int
+
+
+@dataclass
+class SampleRowsTransform:
+ type: Literal[TransformType.SAMPLE_ROWS]
+ n: int
+ replace: bool
+ seed: int
+
+
Transform = Union[
AggregateTransform,
ColumnConversionTransform,
@@ -114,6 +130,8 @@ Transform = Union[
RenameColumnTransform,
SelectColumnsTransform,
SortColumnTransform,
+ ShuffleRowsTransform,
+ SampleRowsTransform,
]