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
fix: change columns in place and add tests (#5763)
Shahmir Varqha7d2149f7c476
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex a600f5d68c..b49080f12d 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -251,10 +251,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):offset = args.page_number * args.page_size# Apply filters, query, and functools.sort using the cached method- result = self._apply_filters_query_sort(- args.query,- args.sort,- )+ result = self._apply_filters_query_sort(args.query, args.sort)# Save the manager to be used for selectiontry:diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py b/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.pyindex 1c8afc5d87..f16429ba44 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py@@ -237,6 +237,11 @@ def python_print_polars(transform.column_id,transform.new_column_id,)+ # Update column names in place+ all_columns[:] = [+ str(new_column_id) if col == column_id else col+ for col in all_columns+ ]return f"{df_name}.rename({{{_as_literal(column_id)}: {_as_literal(new_column_id)}}})" # noqa: E501elif transform.type == TransformType.SORT_COLUMN:@@ -270,10 +275,10 @@ def python_print_polars(for agg_func in aggregations:agg_df = f"{selected_df}.{agg_func}()"rename_dict = {- f"{column}: f'{column}_{agg_func}'" for column in all_columns+ column: f"{column}_{agg_func}" for column in column_ids}agg_df = f"{agg_df}.rename({rename_dict})"- result_df = f"{result_df}.join({agg_df})"+ result_df = f"{result_df}.hstack({agg_df})"return result_dfelif transform.type == TransformType.GROUP_BY:@@ -313,6 +318,8 @@ def python_print_polars(elif transform.type == TransformType.SELECT_COLUMNS:column_ids = transform.column_ids+ # Update columns in place for subsequent transforms+ all_columns[:] = [str(col) for col in column_ids]return f"{df_name}.select({_list_of_strings(column_ids)})"elif transform.type == TransformType.SAMPLE_ROWS:diff --git a/tests/_plugins/ui/_impl/dataframes/test_print_code.py b/tests/_plugins/ui/_impl/dataframes/test_print_code.pyindex b697e6e4f6..5f8ba3e119 100644--- a/tests/_plugins/ui/_impl/dataframes/test_print_code.py+++ b/tests/_plugins/ui/_impl/dataframes/test_print_code.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport astimport datetimeimport string-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, castimport pytestfrom hypothesis import assume, given, settings, strategies as st@@ -41,6 +41,10 @@ from marimo._plugins.ui._impl.dataframes.transforms.types import (TransformType,)+if TYPE_CHECKING:+ import pandas as pd+ import polars as pl+any_column_id = st.one_of(st.text(min_size=1,@@ -585,3 +589,129 @@ def test_print_code_result_matches_actual_transform_ibis(# cast(ibis.Table, code_result).to_polars(),# real_result.to_polars(),# )+++ not DependencyManager.pandas.has() or not DependencyManager.polars.has(),+ reason="pandas or polars not installed",+)+class TestCombinedTransforms:+ @pytest.fixture+ def sample_data(self):+ return {"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}++ @pytest.fixture+ def pd_dataframe(self, sample_data):+ import pandas as pd++ return pd.DataFrame(sample_data)++ @pytest.fixture+ def pl_dataframe(self, sample_data):+ import polars as pl++ return pl.DataFrame(sample_data)++ def _test_transforms(+ self, df: pl.DataFrame | pd.DataFrame, transforms: Transformations+ ):+ import pandas as pd+ import pandas.testing as pd_testing+ import polars as pl+ import polars.testing as pl_testing++ if isinstance(df, pl.DataFrame):+ handler = PolarsTransformHandler()+ print_func = python_print_polars+ testing_func = pl_testing.assert_frame_equal++ elif isinstance(df, pd.DataFrame):+ handler = PandasTransformHandler()+ print_func = python_print_pandas+ testing_func = pd_testing.assert_frame_equal++ result = _apply_transforms(df, handler, transforms)+ code = python_print_transforms(+ "df", df.columns, transforms.transforms, print_func+ )++ # Apply code+ if isinstance(df, pl.DataFrame):+ loc = {"pl": pl, "df": df.clone()}+ exec(code, globals(), loc)+ elif isinstance(df, pd.DataFrame):+ loc = {"pd": pd, "df": df.copy()}+ exec(code, {}, loc)++ assert loc.get("df_next") is not None++ # Test that the result matches the actual result+ testing_func(loc.get("df_next"), result)++ def test_select_then_group_by(+ self, pl_dataframe: pl.DataFrame, pd_dataframe: pd.DataFrame+ ):+ # Apply a select, then a group by+ transforms = Transformations(+ [+ SelectColumnsTransform(+ type=TransformType.SELECT_COLUMNS,+ column_ids=["a", "b"],+ ),+ GroupByTransform(+ type=TransformType.GROUP_BY,+ column_ids=["a"],+ drop_na=False,+ aggregation="sum",+ ),+ ]+ )++ self._test_transforms(pl_dataframe, transforms)+ self._test_transforms(pd_dataframe, transforms)++ def test_select_rename_groupby(+ self, pl_dataframe: pl.DataFrame, pd_dataframe: pd.DataFrame+ ):+ transforms = Transformations(+ [+ SelectColumnsTransform(+ type=TransformType.SELECT_COLUMNS,+ column_ids=["a", "b"],+ ),+ RenameColumnTransform(+ type=TransformType.RENAME_COLUMN,+ column_id="a",+ new_column_id="x",+ ),+ GroupByTransform(+ type=TransformType.GROUP_BY,+ column_ids=["x"],+ drop_na=False,+ aggregation="mean",+ ),+ ]+ )+ self._test_transforms(pl_dataframe, transforms)+ self._test_transforms(pd_dataframe, transforms)++ def test_select_then_aggregate(+ self, pl_dataframe: pl.DataFrame, pd_dataframe: pd.DataFrame+ ):+ """Test select columns followed by aggregate transform."""+ transforms = Transformations(+ [+ SelectColumnsTransform(+ type=TransformType.SELECT_COLUMNS,+ column_ids=["a", "b", "c"],+ ),+ AggregateTransform(+ type=TransformType.AGGREGATE,+ column_ids=["a", "b"],+ aggregations=["sum"],+ ),+ ]+ )++ self._test_transforms(pl_dataframe, transforms)+ self._test_transforms(pd_dataframe, transforms)