A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: Add unique transform to `mo.ui.dataframe` (#4970)
Wasim941ae9e484e0
diff --git a/frontend/src/css/progress.css b/frontend/src/css/progress.cssindex 4f38969767..ee3e0c3d9d 100644--- a/frontend/src/css/progress.css+++ b/frontend/src/css/progress.css@@ -34,6 +34,7 @@width: 100%;display: flex;flex-direction: column;+@apply gap-1 mt-2;}@@ -75,11 +76,13 @@ progress::-webkit-progress-bar {progress::-webkit-progress-value {transition: width 0.2s ease;+@apply bg-blue-500 dark:bg-primary;}progress::-moz-progress-bar {transition: width 0.2s ease;+@apply bg-blue-500 dark:bg-primary;}diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snapindex f2f4450d97..d8eda1057b 100644--- a/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap+++ b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap@@ -1233,6 +1233,119 @@ exports[`renderZodSchema > should render a form sort_column 1`] = `</DocumentFragment>`;+exports[`renderZodSchema > should render a form unique 1`] = `+<DocumentFragment>+ <div+ class="flex flex-row gap-6 items-start"+ >+ <input+ name="type"+ type="hidden"+ value="unique"+ />+ <div+ class="flex flex-row align-start"+ >+ <div+ class="flex flex-col gap-1"+ >+ <label+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+ for=":r31:-form-item"+ >+ Columns+ </label>+ <div+ aria-describedby=":r31:-form-item-description"+ aria-invalid="false"+ class="relative"+ id=":r31:-form-item"+ >+ <div+ aria-controls="radix-:r32:"+ aria-expanded="false"+ aria-haspopup="dialog"+ class="flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px]"+ data-state="closed"+ type="button"+ >+ Select columns+ <svg+ aria-hidden="true"+ class="lucide lucide-chevron-down ml-3 w-4 h-4 opacity-50"+ fill="none"+ height="24"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ viewBox="0 0 24 24"+ width="24"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="m6 9 6 6 6-6"+ />+ </svg>+ </div>+ <div+ class="flex flex-col gap-1 items-start"+ />+ </div>+ </div>+ </div>+ <div+ class="flex flex-row align-start"+ >+ <div+ class="flex flex-col gap-1"+ >+ <label+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"+ for=":r33:-form-item"+ >+ Keep+ </label>+ <button+ aria-autocomplete="none"+ aria-controls="radix-:r34:"+ aria-expanded="false"+ class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"+ data-placeholder=""+ data-state="closed"+ dir="ltr"+ role="combobox"+ type="button"+ >+ <span+ style="pointer-events: none;"+ >+ --+ </span>+ <svg+ aria-hidden="true"+ class="lucide lucide-chevron-down h-4 w-4 opacity-50"+ fill="none"+ height="24"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ viewBox="0 0 24 24"+ width="24"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="m6 9 6 6 6-6"+ />+ </svg>+ </button>+ </div>+ </div>+ </div>+</DocumentFragment>+`;+exports[`renders custom forms column_id 1`] = `<DocumentFragment><div@@ -1240,13 +1353,13 @@ exports[`renders custom forms column_id 1`] = `><labelclass="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"- for=":r31:-form-item"+ for=":r3a:-form-item">Column</label><buttonaria-autocomplete="none"- aria-controls="radix-:r32:"+ aria-controls="radix-:r3b:"aria-expanded="false"class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"data-placeholder=""@@ -1289,18 +1402,18 @@ exports[`renders custom forms column_id_array 1`] = `><labelclass="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"- for=":r38:-form-item"+ for=":r3h:-form-item">Columns</label><div- aria-describedby=":r38:-form-item-description"+ aria-describedby=":r3h:-form-item-description"aria-invalid="false"class="relative"- id=":r38:-form-item"+ id=":r3h:-form-item"><div- aria-controls="radix-:r39:"+ aria-controls="radix-:r3i:"aria-expanded="false"aria-haspopup="dialog"class="flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px]"@@ -1340,13 +1453,13 @@ exports[`renders custom forms column_id_dot_array 1`] = `class="flex flex-col gap-1"><div- aria-describedby=":r3a:-form-item-description"+ aria-describedby=":r3j:-form-item-description"aria-invalid="false"class="relative"- id=":r3a:-form-item"+ id=":r3j:-form-item"><div- aria-controls="radix-:r3b:"+ aria-controls="radix-:r3k:"aria-expanded="false"aria-haspopup="dialog"class="flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px]"@@ -1387,13 +1500,13 @@ exports[`renders custom forms column_id_optional 1`] = `><labelclass="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"- for=":r3c:-form-item"+ for=":r3l:-form-item">Column</label><buttonaria-autocomplete="none"- aria-controls="radix-:r3d:"+ aria-controls="radix-:r3m:"aria-expanded="false"class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"data-placeholder=""diff --git a/frontend/src/plugins/impl/data-frames/panel.tsx b/frontend/src/plugins/impl/data-frames/panel.tsxindex 91418eb514..53cb97faf9 100644--- a/frontend/src/plugins/impl/data-frames/panel.tsx+++ b/frontend/src/plugins/impl/data-frames/panel.tsx@@ -39,6 +39,7 @@ import {Trash2Icon,BracketsIcon,FileJsonIcon,+ CopySlashIcon,} from "lucide-react";import { cn } from "../../../utils/cn";import {@@ -301,4 +302,5 @@ const ICONS: Record<TransformType["type"], React.FC<{ className?: string }>> = {sample_rows: CombineIcon,explode_columns: BracketsIcon,expand_dict: FileJsonIcon,+ unique: CopySlashIcon,};diff --git a/frontend/src/plugins/impl/data-frames/python/__tests__/__snapshots__/python-print.test.ts.snap b/frontend/src/plugins/impl/data-frames/python/__tests__/__snapshots__/python-print.test.ts.snapdeleted file mode 100644index 88ed52de89..0000000000--- a/frontend/src/plugins/impl/data-frames/python/__tests__/__snapshots__/python-print.test.ts.snap+++ /dev/null@@ -1,51 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`pythonPrint: filter > filter_rows > date > != 1`] = `"df[df["my_column"].ne(1000)]"`;--exports[`pythonPrint: filter > filter_rows > date > < 1`] = `"df[df["my_column"] < 1000]"`;--exports[`pythonPrint: filter > filter_rows > date > <= 1`] = `"df[df["my_column"] <= 1000]"`;--exports[`pythonPrint: filter > filter_rows > date > == 1`] = `"df[df["my_column"] == 1000]"`;--exports[`pythonPrint: filter > filter_rows > date > > 1`] = `"df[df["my_column"] > 1000]"`;--exports[`pythonPrint: filter > filter_rows > date > >= 1`] = `"df[df["my_column"] >= 1000]"`;--exports[`pythonPrint: filter > filter_rows > date > is_false 1`] = `"df[df["my_column"].eq(False)]"`;--exports[`pythonPrint: filter > filter_rows > date > is_nan 1`] = `"df[df["my_column"].isna()]"`;--exports[`pythonPrint: filter > filter_rows > date > is_not_nan 1`] = `"df[df["my_column"].notna()]"`;--exports[`pythonPrint: filter > filter_rows > date > is_true 1`] = `"df[df["my_column"].eq(True)]"`;--exports[`pythonPrint: filter > filter_rows > number > != 1`] = `"df[df["my_column"].ne(42)]"`;--exports[`pythonPrint: filter > filter_rows > number > < 1`] = `"df[df["my_column"] < 42]"`;--exports[`pythonPrint: filter > filter_rows > number > <= 1`] = `"df[df["my_column"] <= 42]"`;--exports[`pythonPrint: filter > filter_rows > number > == 1`] = `"df[df["my_column"] == 42]"`;--exports[`pythonPrint: filter > filter_rows > number > > 1`] = `"df[df["my_column"] > 42]"`;--exports[`pythonPrint: filter > filter_rows > number > >= 1`] = `"df[df["my_column"] >= 42]"`;--exports[`pythonPrint: filter > filter_rows > number > is_nan 1`] = `"df[df["my_column"].isna()]"`;--exports[`pythonPrint: filter > filter_rows > number > is_not_nan 1`] = `"df[df["my_column"].notna()]"`;--exports[`pythonPrint: filter > filter_rows > string > contains 1`] = `"df[df["my_column"].str.contains("val")]"`;--exports[`pythonPrint: filter > filter_rows > string > does_not_equal 1`] = `"df[df["my_column"].ne("val")]"`;--exports[`pythonPrint: filter > filter_rows > string > ends_with 1`] = `"df[df["my_column"].str.endswith("val")]"`;--exports[`pythonPrint: filter > filter_rows > string > equals 1`] = `"df[df["my_column"].eq("val")]"`;--exports[`pythonPrint: filter > filter_rows > string > in 1`] = `"df[df["my_column"].isin("val")]"`;--exports[`pythonPrint: filter > filter_rows > string > regex 1`] = `"df[df["my_column"].str.contains("val", regex=True)]"`;--exports[`pythonPrint: filter > filter_rows > string > starts_with 1`] = `"df[df["my_column"].str.startswith("val")]"`;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.tsdeleted file mode 100644index b0d8f40ee2..0000000000--- a/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts+++ /dev/null@@ -1,360 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import { pythonPrint } from "@/plugins/impl/data-frames/python/python-print";-import type { TransformType } from "@/plugins/impl/data-frames/schema";-import { expect, describe, it } from "vitest";-import {- BOOLEAN_OPERATORS,- DATE_OPERATORS,- NUMERIC_OPERATORS,- STRING_OPERATORS,-} from "../../utils/operators";-import { Objects } from "@/utils/objects";-import type { ColumnId } from "../../types";--describe("pythonPrint", () => {- // Test for column_conversion- it("generates correct Python code for column_conversion", () => {- const transform: TransformType = {- type: "column_conversion",- column_id: "my_column" as ColumnId,- data_type: "int8",- errors: "ignore",- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(- `"df["my_column"].astype("int8", errors="ignore")"`,- );- });-- it("generates correct Python code for column_conversion, for numeric columns", () => {- const transform: TransformType = {- type: "column_conversion",- column_id: 1 as ColumnId,- data_type: "int8",- errors: "ignore",- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(- `"df[1].astype("int8", errors="ignore")"`,- );- });-- // Test for rename_column- it("generates correct Python code for rename_column", () => {- const transform: TransformType = {- type: "rename_column",- column_id: "old_name" as ColumnId,- new_column_id: "new_name" as ColumnId,- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(- `"df.rename(columns={"old_name": "new_name"})"`,- );- });-- it("generates correct Python code for rename_column, for numeric columns", () => {- const transform: TransformType = {- type: "rename_column",- column_id: 1 as ColumnId,- new_column_id: 2 as ColumnId,- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(`"df.rename(columns={1: 2})"`);- });-- // Test for sort_column- it("generates correct Python code for sort_column", () => {- const transform: TransformType = {- type: "sort_column",- column_id: "my_column" as ColumnId,- ascending: false,- na_position: "first",- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(- `"df.sort_values(by="my_column", ascending=False, na_position="first")"`,- );- });-- // Test for aggregate- it("generates correct Python code for aggregate", () => {- const transform: TransformType = {- type: "aggregate",- column_ids: ["my_column"] as ColumnId[],- aggregations: ["mean"],- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(`"df.agg({"my_column": ["mean"]})"`);-- const transform2: TransformType = {- type: "aggregate",- column_ids: [] as ColumnId[],- aggregations: ["mean"],- };- const result2 = pythonPrint("df", transform2);- expect(result2).toMatchInlineSnapshot(`"df.agg(["mean"])"`);-- const transform3: TransformType = {- type: "aggregate",- column_ids: [2] as ColumnId[],- aggregations: ["mean", "sum"],- };- const result3 = pythonPrint("df", transform3);- expect(result3).toMatchInlineSnapshot(`"df.agg({2: ["mean", "sum"]})"`);- });-- // Test for group_by- it("generates correct Python code for group_by", () => {- const transform: TransformType = {- type: "group_by",- column_ids: ["my_column"] as ColumnId[],- aggregation: "sum",- drop_na: true,- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(- `"df.groupby(["my_column"], dropna=True).sum()"`,- );-- const transform2: TransformType = {- type: "group_by",- column_ids: ["my_column", "my_column2", 3] as ColumnId[],- aggregation: "sum",- drop_na: false,- };- const result2 = pythonPrint("df", transform2);- expect(result2).toMatchInlineSnapshot(- `"df.groupby(["my_column", "my_column2", 3]).sum()"`,- );-- const transform3: TransformType = {- type: "group_by",- column_ids: ["my_column"] as ColumnId[],- aggregation: "mean",- drop_na: false,- };- const result3 = pythonPrint("df", transform3);- expect(result3).toMatchInlineSnapshot(- `"df.groupby(["my_column"]).mean(numeric_only=True)"`,- );-- const transform4: TransformType = {- type: "group_by",- column_ids: ["my_column"] as ColumnId[],- aggregation: "median",- drop_na: false,- };- const result4 = pythonPrint("df", transform4);- expect(result4).toMatchInlineSnapshot(- `"df.groupby(["my_column"]).median(numeric_only=True)"`,- );- });-});--// Test for select_columns-it("generates correct Python code for select_columns", () => {- const transform: TransformType = {- type: "select_columns",- column_ids: ["my_column"] as ColumnId[],- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(`"df["my_column"]"`);-- const transform2: TransformType = {- type: "select_columns",- column_ids: ["my_column", "my_column2", 3] as ColumnId[],- };- const result2 = pythonPrint("df", transform2);- expect(result2).toMatchInlineSnapshot(`"df[["my_column", "my_column2", 3]]"`);-});--// 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", {- type: "filter_rows",- operation: "keep_rows",- where: [- {- column_id: "my_column" as ColumnId,- operator: "==",- value: 42,- },- ],- });- expect(result).toMatchInlineSnapshot(`"df[df["my_column"] == 42]"`);-- const result2 = pythonPrint("df", {- type: "filter_rows",- operation: "remove_rows",- where: [- {- column_id: "my_column" as ColumnId,- operator: "==",- value: 42,- },- ],- });- expect(result2).toMatchInlineSnapshot(`"df[~((df["my_column"] == 42))]"`);- });-- it("handle where clauses with numeric columns", () => {- const result = pythonPrint("df", {- type: "filter_rows",- operation: "keep_rows",- where: [- {- column_id: 2 as ColumnId,- operator: "==",- value: 43,- },- ],- });- expect(result).toMatchInlineSnapshot(`"df[df[2] == 43]"`);- });-- it("handle multiple where clauses", () => {- const result = pythonPrint("df", {- type: "filter_rows",- operation: "keep_rows",- where: [- {- column_id: "my_column" as ColumnId,- operator: "==",- value: 42,- },- {- column_id: 2 as ColumnId,- operator: "==",- value: 43,- },- ],- });- expect(result).toMatchInlineSnapshot(- `"df[(df["my_column"] == 42) & (df[2] == 43)]"`,- );- });-- // Test for filter_rows for strings- it.each(Objects.entries(STRING_OPERATORS))(- "filter_rows > string > %s",- (operator) => {- const transform: TransformType = {- type: "filter_rows",- operation: "keep_rows",- where: [- {- column_id: "my_column" as ColumnId,- operator: operator,- value: "val",- },- ],- };- const result = pythonPrint("df", transform);- expect(result).toMatchSnapshot();- },- );-- // Test for filter_rows for booleans- it.each(Objects.entries(BOOLEAN_OPERATORS))(- "filter_rows > date > %s",- (operator) => {- const transform: TransformType = {- type: "filter_rows",- operation: "keep_rows",- where: [- {- column_id: "my_column" as ColumnId,- operator: operator,- value: true,- },- ],- };- const result = pythonPrint("df", transform);- expect(result).toMatchSnapshot();- },- );-- // Test for filter_rows for dates- it.each(Objects.entries(DATE_OPERATORS))(- "filter_rows > date > %s",- (operator) => {- const transform: TransformType = {- type: "filter_rows",- operation: "keep_rows",- where: [- {- column_id: "my_column" as ColumnId,- operator: operator,- value: 1000,- },- ],- };- const result = pythonPrint("df", transform);- expect(result).toMatchSnapshot();- },- );-- // Test for filter_rows for numbers- it.each(Objects.entries(NUMERIC_OPERATORS))(- "filter_rows > number > %s",- (operator) => {- const transform: TransformType = {- type: "filter_rows",- operation: "keep_rows",- where: [- {- column_id: "my_column" as ColumnId,- operator: operator,- value: 42,- },- ],- };- const result = pythonPrint("df", transform);- expect(result).toMatchSnapshot();- },- );-- // Test for explode_column- it("generates correct Python code for explode_column", () => {- const transform: TransformType = {- type: "explode_columns",- column_ids: ["my_column"] as ColumnId[],- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(`"df.explode(["my_column"])"`);- });-- // Test for expand_dict- it("generates correct Python code for expand_dict", () => {- const transform: TransformType = {- type: "expand_dict",- column_id: "my_column" as ColumnId,- };- const result = pythonPrint("df", transform);- expect(result).toMatchInlineSnapshot(- `"df.join(pd.DataFrame(df.pop("my_column").values.tolist()))"`,- );- });-});diff --git a/frontend/src/plugins/impl/data-frames/python/python-print.ts b/frontend/src/plugins/impl/data-frames/python/python-print.tsdeleted file mode 100644index 8e1577e269..0000000000--- a/frontend/src/plugins/impl/data-frames/python/python-print.ts+++ /dev/null@@ -1,194 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import type { TransformType } from "@/plugins/impl/data-frames/schema";-import { logNever } from "@/utils/assertNever";-import type { OperatorType } from "../utils/operators";-import type { ColumnId } from "../types";--export function pythonPrintTransforms(- dfName: string,- transforms: TransformType[],-): string {- const dfNextName = `${dfName}_next`;- const transformStrs = transforms.map(- (transform) => `${dfNextName} = ${pythonPrint(dfNextName, transform)}`,- );-- return [`${dfNextName} = ${dfName}`, ...transformStrs].join("\n");-}--export function pythonPrint(dfName: string, transform: TransformType): string {- switch (transform.type) {- case "column_conversion": {- const { column_id, data_type, errors } = transform;- return `${dfName}[${asLiteral(- column_id,- )}].astype("${data_type}", errors="${errors}")`;- }- case "rename_column": {- const { column_id, new_column_id } = transform;- return `${dfName}.rename(columns={${asLiteral(column_id)}: ${asLiteral(- new_column_id,- )}})`;- }- case "sort_column": {- const { column_id, ascending, na_position } = transform;- const args = argsList(- `by=${asLiteral(column_id)}`,- ascending ? "" : "ascending=False",- na_position === "last" ? "" : `na_position="${na_position}"`,- );- return `${dfName}.sort_values(${args})`;- }- case "filter_rows": {- const { operation, where } = transform;- if (where.length === 0) {- return dfName;- }-- const whereClauses = where.map((condition) =>- generateWhereClause(dfName, condition),- );- if (operation === "keep_rows" && whereClauses.length === 1) {- return `${dfName}[${whereClauses[0]}]`;- }-- const expression = whereClauses- .map((clause) => `(${clause})`)- .join(" & ");-- return operation === "keep_rows"- ? `${dfName}[${expression}]`- : `${dfName}[~(${expression})]`;- }- case "aggregate": {- const { column_ids, aggregations } = transform;- if (column_ids.length === 0) {- return `${dfName}.agg(${listOfStrings(aggregations)})`;- }- return `${dfName}.agg({${column_ids- .map(- (columnId) =>- `${asLiteral(columnId)}: ${listOfStrings(aggregations)}`,- )- .join(", ")}})`;- }- case "group_by": {- const { column_ids, aggregation, drop_na } = transform;- const args = argsList(- listOfStrings(column_ids),- drop_na ? "dropna=True" : "",- );- let aggArgs = "";- if (aggregation === "mean") {- aggArgs = "numeric_only=True";- } else if (aggregation === "median") {- aggArgs = "numeric_only=True";- }- return `${dfName}.groupby(${args}).${aggregation}(${aggArgs})`;- }- case "select_columns": {- const { column_ids } = transform;- if (column_ids.length === 0) {- return dfName;- }- if (column_ids.length === 1) {- return `${dfName}[${asLiteral(column_ids[0])}]`;- }- return `${dfName}[${listOfStrings(column_ids)}]`;- }- case "sample_rows": {- const { n } = transform;- return `${dfName}.sample(n=${n})`;- }- case "shuffle_rows":- return `${dfName}.sample(frac=1)`;- case "explode_columns": {- const { column_ids } = transform;- return `${dfName}.explode(${listOfStrings(column_ids)})`;- }- case "expand_dict": {- const columnId = asLiteral(transform.column_id);- const args = `df.pop(${columnId}).values.tolist())`;- return `${dfName}.join(pd.DataFrame(${args})`;- }- default:- logNever(transform);- return "";- }-}--function generateWhereClause(- dfName: string,- where: {- column_id: ColumnId;- operator: OperatorType;- value?: unknown;- },-): string {- const { column_id, operator, value } = where;- switch (operator) {- case "==":- return `${dfName}[${asLiteral(column_id)}] == ${asLiteral(value)}`;- case "equals":- return `${dfName}[${asLiteral(column_id)}].eq(${asLiteral(value)})`;- case "does_not_equal":- return `${dfName}[${asLiteral(column_id)}].ne(${asLiteral(value)})`;- case "contains":- return `${dfName}[${asLiteral(column_id)}].str.contains(${asLiteral(- value,- )})`;- case "regex":- return `${dfName}[${asLiteral(column_id)}].str.contains(${asLiteral(- value,- )}, regex=True)`;- case "starts_with":- return `${dfName}[${asLiteral(column_id)}].str.startswith(${asLiteral(- value,- )})`;- case "ends_with":- return `${dfName}[${asLiteral(column_id)}].str.endswith(${asLiteral(- value,- )})`;- case "in":- return `${dfName}[${asLiteral(column_id)}].isin(${listOfStrings(value)})`;- case "!=":- return `${dfName}[${asLiteral(column_id)}].ne(${asLiteral(value)})`;- case ">":- return `${dfName}[${asLiteral(column_id)}] > ${asLiteral(value)}`;- case ">=":- return `${dfName}[${asLiteral(column_id)}] >= ${asLiteral(value)}`;- case "<":- return `${dfName}[${asLiteral(column_id)}] < ${asLiteral(value)}`;- case "<=":- return `${dfName}[${asLiteral(column_id)}] <= ${asLiteral(value)}`;- case "is_nan":- return `${dfName}[${asLiteral(column_id)}].isna()`;- case "is_not_nan":- return `${dfName}[${asLiteral(column_id)}].notna()`;- case "is_true":- return `${dfName}[${asLiteral(column_id)}].eq(True)`;- case "is_false":- return `${dfName}[${asLiteral(column_id)}].eq(False)`;- default:- logNever(operator);- return "df";- }-}--function asLiteral(value: unknown): string {- if (typeof value === "string") {- return `"${value}"`;- }- return `${value}`;-}--function listOfStrings(value: unknown): string {- if (Array.isArray(value)) {- return `[${value.map(asLiteral).join(", ")}]`;- }- return asLiteral(value);-}--function argsList(...args: string[]): string {- return args.filter(Boolean).join(", ");-}diff --git a/frontend/src/plugins/impl/data-frames/schema.ts b/frontend/src/plugins/impl/data-frames/schema.tsindex c38c319f7c..49f62f96b1 100644--- a/frontend/src/plugins/impl/data-frames/schema.ts+++ b/frontend/src/plugins/impl/data-frames/schema.ts@@ -170,6 +170,17 @@ const ExpandDictTransformSchema = z.object({column_id: column_id,});+const UniqueTransformSchema = z+ .object({+ type: z.literal("unique"),+ column_ids: column_id_array,+ keep: z+ .enum(["first", "last", "none", "any"])+ .default("first")+ .describe(FieldOptions.of({ label: "Keep" })),+ })+ .describe(FieldOptions.of({ direction: "row" }));+export const TransformTypeSchema = z.union([FilterRowsTransformSchema,SelectColumnsTransformSchema,@@ -182,6 +193,7 @@ export const TransformTypeSchema = z.union([ShuffleRowsTransformSchema,ExplodeColumnsTransformSchema,ExpandDictTransformSchema,+ UniqueTransformSchema,]);export type TransformType = z.infer<typeof TransformTypeSchema>;diff --git a/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts b/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.tsindex 905367b212..54817f2bd6 100644--- a/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts+++ b/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts@@ -56,6 +56,11 @@ const Transforms = {type: "expand_dict",column_id: "col1" as ColumnId,} satisfies TransformType,+ UNIQUE: {+ type: "unique",+ column_ids: ["col1"] as ColumnId[],+ keep: "first",+ } satisfies TransformType,};describe("getUpdatedColumnTypes", () => {@@ -152,6 +157,20 @@ describe("getUpdatedColumnTypes", () => {`);});+ it("should update column types for unique conversion", () => {+ const result = getUpdatedColumnTypes(+ [Transforms.UNIQUE],+ INITIAL_COLUMN_TYPES,+ );+ expect(result).toMatchInlineSnapshot(`+ Map {+ "col1" => "str",+ 2 => "bool",+ "col3" => "int",+ }+ `);+ });+it("can chain multiple transforms", () => {const result = getUpdatedColumnTypes([diff --git a/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.tsindex a60ba3535c..9f53ff5910 100644--- a/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts+++ b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts@@ -58,6 +58,7 @@ function handleTransform(case "sort_column":case "expand_dict":case "explode_columns":+ case "unique":return next;default:logNever(transform);diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py b/marimo/_plugins/ui/_impl/dataframes/transforms/apply.pyindex 26c2d697c7..0be0b99a05 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py@@ -23,28 +23,29 @@ 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:+ if transform.type is TransformType.RENAME_COLUMN:return handler.handle_rename_column(df, transform)- elif transform.type is TransformType.SORT_COLUMN:+ if transform.type is TransformType.SORT_COLUMN:return handler.handle_sort_column(df, transform)- elif transform.type is TransformType.FILTER_ROWS:+ if transform.type is TransformType.FILTER_ROWS:return handler.handle_filter_rows(df, transform)- elif transform.type is TransformType.GROUP_BY:+ if transform.type is TransformType.GROUP_BY:return handler.handle_group_by(df, transform)- elif transform.type is TransformType.AGGREGATE:+ if transform.type is TransformType.AGGREGATE:return handler.handle_aggregate(df, transform)- elif transform.type is TransformType.SELECT_COLUMNS:+ if transform.type is TransformType.SELECT_COLUMNS:return handler.handle_select_columns(df, transform)- elif transform.type is TransformType.SHUFFLE_ROWS:+ if transform.type is TransformType.SHUFFLE_ROWS:return handler.handle_shuffle_rows(df, transform)- elif transform.type is TransformType.SAMPLE_ROWS:+ if transform.type is TransformType.SAMPLE_ROWS:return handler.handle_sample_rows(df, transform)- elif transform.type is TransformType.EXPLODE_COLUMNS:+ if transform.type is TransformType.EXPLODE_COLUMNS:return handler.handle_explode_columns(df, transform)- elif transform.type is TransformType.EXPAND_DICT:+ if transform.type is TransformType.EXPAND_DICT:return handler.handle_expand_dict(df, transform)- else:- assert_never(transform.type)+ if transform.type is TransformType.UNIQUE:+ return handler.handle_unique(df, transform)+ assert_never(transform.type)def _apply_transforms(diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.pyindex 7527f09c65..c1ae7212c7 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport datetimefrom collections.abc import Sequence-from typing import TYPE_CHECKING, Any, Callable, Optional, cast+from typing import TYPE_CHECKING, Any, Callable, NoReturn, Optional, castfrom marimo._plugins.ui._impl.dataframes.transforms.print_code import (python_print_ibis,@@ -25,6 +25,7 @@ from marimo._plugins.ui._impl.dataframes.transforms.types import (SortColumnTransform,Transform,TransformHandler,+ UniqueTransform,)from marimo._utils.assert_never import assert_never@@ -223,6 +224,20 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):df_name, columns, transforms, python_print_pandas)+ @staticmethod+ def handle_unique(+ df: pd.DataFrame, transform: UniqueTransform+ ) -> pd.DataFrame:+ if transform.keep == "first":+ return df.drop_duplicates(+ subset=transform.column_ids, keep="first"+ )+ if transform.keep == "last":+ return df.drop_duplicates(subset=transform.column_ids, keep="last")+ if transform.keep == "none":+ return df.drop_duplicates(subset=transform.column_ids, keep=False)+ assert_never(cast(NoReturn, transform.keep))+class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethod@@ -467,6 +482,22 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):df_name, columns, transforms, python_print_polars)+ @staticmethod+ def handle_unique(+ df: pl.DataFrame, transform: UniqueTransform+ ) -> pl.DataFrame:+ keep = transform.keep+ if (+ keep == "first"+ or keep == "last"+ or keep == "any"+ or keep == "none"+ ):+ return df.unique(+ subset=cast(Sequence[str], transform.column_ids), keep=keep+ )+ assert_never(keep)+class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethod@@ -661,6 +692,18 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):) -> ibis.Table:return df.unpack(transform.column_id)+ @staticmethod+ def handle_unique(+ df: ibis.Table, transform: UniqueTransform+ ) -> ibis.Table:+ if transform.keep == "first":+ return df.distinct(on=transform.column_ids, keep="first")+ if transform.keep == "last":+ return df.distinct(on=transform.column_ids, keep="last")+ if transform.keep == "none":+ return df.distinct(on=transform.column_ids, keep=None)+ assert_never(cast(NoReturn, transform.keep))+@staticmethoddef as_python_code(df_name: str, columns: list[str], transforms: list[Transform]diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py b/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.pyindex 5f683a210f..451148961b 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py@@ -178,6 +178,10 @@ def python_print_pandas(args = f"{df_name}.pop({column_id}).values.tolist()"return f"{df_name}.join(pd.DataFrame({args}))"+ elif transform.type == TransformType.UNIQUE:+ column_ids = transform.column_ids+ return f"{df_name}.drop_duplicates({_list_of_strings(column_ids)}, keep={_as_literal(transform.keep)})"+assert_never(transform.type)@@ -325,6 +329,11 @@ def python_print_polars(elif transform.type == TransformType.EXPAND_DICT:column_id = _as_literal(transform.column_id)return f"{df_name}.hstack(pl.DataFrame({df_name}.select({column_id}).to_series().to_list())).drop({column_id})" # noqa: E501++ elif transform.type == TransformType.UNIQUE:+ column_ids = transform.column_ids+ return f"{df_name}.unique(subset={_list_of_strings(column_ids)}, keep={_as_literal(transform.keep)})" # noqa: E501+assert_never(transform.type)@@ -453,6 +462,10 @@ def python_print_ibis(column_id = transform.column_idreturn f"{df_name}.unpack({_as_literal(column_id)})"+ elif transform.type == TransformType.UNIQUE:+ column_ids = transform.column_ids+ return f"{df_name}.distinct(on={_list_of_strings(column_ids)}, keep={_as_literal(transform.keep)})" # noqa: E501+assert_never(transform.type)diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/types.py b/marimo/_plugins/ui/_impl/dataframes/transforms/types.pyindex 7fbbe1e59a..1a19a1ab1f 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/types.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/types.py@@ -47,6 +47,7 @@ Aggregation = Literal["min","max",]+UniqueKeep = Literal["first", "last", "none", "any"]class TransformType(Enum):@@ -61,6 +62,7 @@ class TransformType(Enum):SAMPLE_ROWS = "sample_rows"EXPLODE_COLUMNS = "explode_columns"EXPAND_DICT = "expand_dict"+ UNIQUE = "unique"@dataclass(frozen=True)@@ -163,6 +165,13 @@ class ExpandDictTransform:column_id: ColumnId+@dataclass+class UniqueTransform:+ type: Literal[TransformType.UNIQUE]+ column_ids: ColumnIds+ keep: UniqueKeep++Transform = Union[AggregateTransform,ColumnConversionTransform,@@ -175,6 +184,7 @@ Transform = Union[SampleRowsTransform,ExplodeColumnsTransform,ExpandDictTransform,+ UniqueTransform,]@@ -244,6 +254,11 @@ class TransformHandler(abc.ABC, Generic[T]):def handle_expand_dict(df: T, transform: ExpandDictTransform) -> T:raise NotImplementedError+ @staticmethod+ @abc.abstractmethod+ def handle_unique(df: T, transform: UniqueTransform) -> T:+ raise NotImplementedError+@staticmethoddef as_python_code(df_name: str, columns: list[str], transforms: list[Transform]diff --git a/marimo/_smoke_tests/issues/4970-unique-transform.py b/marimo/_smoke_tests/issues/4970-unique-transform.pynew file mode 100644index 0000000000..36136c6887--- /dev/null+++ b/marimo/_smoke_tests/issues/4970-unique-transform.py@@ -0,0 +1,67 @@+import marimo++__generated_with = "0.13.10"+app = marimo.App(width="columns")++[email protected](column=0)+def _(df_pandas, mo):+ mo.ui.dataframe(df_pandas)+ return+++def _(df_polars, mo):+ mo.ui.dataframe(df_polars)+ return+++def _(df_ibis, mo):+ mo.ui.dataframe(df_ibis)+ return+++def _():+ import marimo as mo+ import pandas as pd+ import polars as pl+ import ibis as ib+ from vega_datasets import data+ return data, ib, mo, pd, pl+++def _(data, ib, pd, pl):+ iris_dataset = data.iris()+ df_pandas = pd.DataFrame(iris_dataset)+ df_polars = pl.DataFrame(iris_dataset)+ df_ibis = ib.memtable(iris_dataset)+ return df_ibis, df_pandas, df_polars++[email protected](column=1)+def _(df_pandas):+ df_pandas_next = df_pandas+ df_pandas_next.drop_duplicates(["sepalLength"], keep="first")+ return+++def _(df_polars):+ df_polars_next = df_polars+ df_polars_next.unique(subset=["sepalLength"], keep="first")+ return+++def _(df_ibis, mo):+ df_ibis_next = df_ibis+ df_ibis_next = df_ibis_next.distinct(on=["sepalLength"], keep="first")+ mo.ui.table(df_ibis_next)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/dataframes/test_handlers.py b/tests/_plugins/ui/_impl/dataframes/test_handlers.pyindex 9194006460..523d544f2c 100644--- a/tests/_plugins/ui/_impl/dataframes/test_handlers.py+++ b/tests/_plugins/ui/_impl/dataframes/test_handlers.py@@ -30,6 +30,7 @@ from marimo._plugins.ui._impl.dataframes.transforms.types import (Transform,Transformations,TransformType,+ UniqueTransform,)HAS_DEPS = (@@ -1151,6 +1152,86 @@ class TestTransformHandler:result[sorted(result.columns)],)+ @staticmethod+ @pytest.mark.parametrize(+ (+ "df",+ "expected_first",+ "expected_last",+ "expected_none",+ "expected_any",+ ),+ [+ (+ pd.DataFrame(+ {"A": ["a", "a", "b", "b", "c"], "B": [1, 2, 3, 4, 5]}+ ),+ pd.DataFrame({"A": ["a", "b", "c"], "B": [1, 3, 5]}),+ pd.DataFrame({"A": ["a", "b", "c"], "B": [2, 4, 5]}),+ pd.DataFrame({"A": ["c"], "B": [5]}),+ pd.DataFrame(),+ ),+ (+ pl.DataFrame(+ {"A": ["a", "a", "b", "b", "c"], "B": [1, 2, 3, 4, 5]}+ ),+ pl.DataFrame({"A": ["a", "b", "c"], "B": [1, 3, 5]}),+ pl.DataFrame({"A": ["a", "b", "c"], "B": [2, 4, 5]}),+ pl.DataFrame({"A": ["c"], "B": [5]}),+ pl.DataFrame({"A": ["a", "b", "c"], "B": [1, 3, 5]}),+ ),+ (+ ibis.memtable(+ {"A": ["a", "a", "b", "b", "c"], "B": [1, 2, 3, 4, 5]}+ ),+ ibis.memtable({"A": ["a", "b", "c"], "B": [1, 3, 5]}),+ ibis.memtable({"A": ["a", "b", "c"], "B": [2, 4, 5]}),+ ibis.memtable({"A": ["c"], "B": [5]}),+ ibis.memtable({}),+ ),+ ],+ )+ def test_unique(+ df: DataFrameType,+ expected_first: DataFrameType,+ expected_last: DataFrameType,+ expected_none: DataFrameType,+ expected_any: DataFrameType,+ ) -> None:+ for keep, expected in [+ ("first", expected_first),+ ("last", expected_last),+ ("none", expected_none),+ ]:+ transform = UniqueTransform(+ type=TransformType.UNIQUE, column_ids=["A"], keep=keep+ )+ result = apply(df, transform)+ if isinstance(result, pd.DataFrame):+ assert_frame_equal(+ expected[expected.columns],+ result[result.columns],+ )+ else:+ # The result is not deterministic for Polars and Ibis dataframes.+ if isinstance(result, ibis.Table):+ result = result.to_polars()+ expected = expected.to_polars()+ assert result["A"].n_unique() == expected["A"].n_unique()+ assert result.columns == expected.columns+ assert result.shape == expected.shape+ assert result.dtypes == expected.dtypes++ if isinstance(df, pl.DataFrame):+ transform = UniqueTransform(+ type=TransformType.UNIQUE, column_ids=["A"], keep="any"+ )+ result = apply(df, transform)+ assert result["A"].n_unique() == expected_any["A"].n_unique()+ assert result.columns == expected_any.columns+ assert result.shape == expected_any.shape+ assert result.dtypes == expected_any.dtypes+@staticmethod@pytest.mark.parametrize(("df", "expected", "expected2"),