From 6413410f6d2ff2c3c3cdeafed76ad542fd919314 Mon Sep 17 00:00:00 2001 From: Anish Mehta Date: Sat, 28 Nov 2026 14:23:24 +0530 Subject: [PATCH] [Python] Fix DataFrame min and max on empty or all-NA partitions --- CHANGES.md | 1 + sdks/python/apache_beam/dataframe/frames.py | 38 +++++++++++++++++-- .../apache_beam/dataframe/frames_test.py | 26 +++++++++++++ .../apache_beam/dataframe/transforms_test.py | 9 +++++ 4 files changed, 70 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index cacff24ea2ab..8f582d187eae 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -198,6 +198,7 @@ * (Java) Fixed JmsIO leaving most messages unacknowledged, and so redelivered, on runners that execute unbounded sources as splittable DoFns, such as Dataflow Runner v2. Reporting progress for an unbounded source no longer takes a checkpoint, and finalizing a JmsIO checkpoint, or resuming from it, also acknowledges the earlier checkpoints of the same reader ([#41013](https://github.com/apache/beam/pull/41013)). * (Python) Fixed the DataFrame API `idxmin()` and `idxmax()` failing with `ValueError` when a partition is empty, for example after a filter, or when a datetime column has only `NaT` in a partition ([#41662](https://github.com/apache/beam/issues/41662)). * (Python) Fixed local file patterns that use `/`, such as `data/*.txt`, matching no files on Windows: `ReadFromText` raised "No files found", and `ReadAllFromText` and `fileio.MatchFiles` returned nothing ([#41618](https://github.com/apache/beam/issues/41618)). +* (Python) Fixed the DataFrame API `min()` and `max()` raising `TypeError` on timedelta, tz-aware datetime, `string` and nullable columns when a partition has only missing values, and returning NaN with `skipna=False` when a partition is empty ([#41732](https://github.com/apache/beam/issues/41732)). ## Security Fixes diff --git a/sdks/python/apache_beam/dataframe/frames.py b/sdks/python/apache_beam/dataframe/frames.py index c3baccec7d4b..bbbc568fc087 100644 --- a/sdks/python/apache_beam/dataframe/frames.py +++ b/sdks/python/apache_beam/dataframe/frames.py @@ -2091,12 +2091,42 @@ def aggregate(self, func, axis, *args, **kwargs): agg_kwargs = kwargs.copy() if ((_is_associative(base_func) or _is_liftable_with_sum(base_func)) and singleton_reason is None): + + def to_series(s): + # Coerce to a Series, if the result is scalar we still want a + # Series so we can combine and do the final aggregation next. + return pd.Series(s.agg(func, *args, **kwargs)) + + if _check_str_or_np_builtin(base_func, ['min', 'max']): + + def pre_aggregate(s): + # An empty partition has no min or max (pandas gives NaN, even + # with skipna=False), so it adds nothing to the final step. + if len(s) == 0: + return s + # Keep the dtype of the input. pd.Series() would turn the NaT or + # NA of an all-NA partition into datetime64 or object, which + # can't be combined with the other partitions. + result = s.agg(func, *args, **kwargs) + if isinstance(result, pd.Series): + return pd.Series( + result.tolist(), + index=result.index, + name=result.name, + dtype=s.dtype) + return pd.Series([result], dtype=s.dtype) + + # pre_aggregate gives an empty Series for the (empty) proxy, keep + # the proxy that to_series gives instead. + intermediate_proxy = to_series(self._expr.proxy()) + else: + pre_aggregate = to_series + intermediate_proxy = None + intermediate = expressions.ComputedExpression( f'pre_aggregate_{base_func}', - # Coerce to a Series, if the result is scalar we still want a Series - # so we can combine and do the final aggregation next. - lambda s: pd.Series(s.agg(func, *args, **kwargs)), - [self._expr], + pre_aggregate, [self._expr], + proxy=intermediate_proxy, requires_partition_by=partitionings.Arbitrary(), preserves_partition_by=partitionings.Singleton()) allow_nonparallel_final = True diff --git a/sdks/python/apache_beam/dataframe/frames_test.py b/sdks/python/apache_beam/dataframe/frames_test.py index aa3151a1cc1c..bd7a042deaa7 100644 --- a/sdks/python/apache_beam/dataframe/frames_test.py +++ b/sdks/python/apache_beam/dataframe/frames_test.py @@ -2320,6 +2320,32 @@ def test_agg_list_with_count_and_size(self): df = pd.DataFrame({'A': [1.0, None, 3.0, 4.0], 'B': [2, 3, 5, 7]}) self._run_test(lambda df: df.agg(['count', 'mean']), df) + def test_min_max_all_na_partition(self): + # Each test partition holds a single row here, so the NA rows make + # partitions with only missing values. + df = pd.DataFrame({ + 'td': pd.to_timedelta([None, 5, None, 2], unit='s'), + 'tz': pd.to_datetime([None, '2024-01-05', None, + '2024-01-02']).tz_localize('UTC'), + 'int': pd.array([None, 5, None, 2], dtype='Int64'), + 'str': pd.array([None, 'b', None, 'a'], dtype='string'), + }) + # TODO(https://github.com/apache/beam/issues/20926): max and min produce + # the wrong proxy + for column in df.columns: + with self.subTest(column=column): + s = df[column] + self._run_test(lambda s: s.min(), s, check_proxy=False) + self._run_test(lambda s: s.max(), s, check_proxy=False) + self._run_test(lambda s: s.agg(['min', 'max']), s, check_proxy=False) + self._run_test( + lambda s: s.agg(['min', 'max'], skipna=False), s, check_proxy=False) + self._run_test(lambda df: df.min(numeric_only=False), df, check_proxy=False) + self._run_test( + lambda df: df.max(skipna=False, numeric_only=False), + df, + check_proxy=False) + @unittest.skipIf(PD_VERSION >= (2, 0), "level argument removed in Pandas 2") def test_series_agg_level(self): self._run_test( diff --git a/sdks/python/apache_beam/dataframe/transforms_test.py b/sdks/python/apache_beam/dataframe/transforms_test.py index ed78284217dd..f7ad4273af02 100644 --- a/sdks/python/apache_beam/dataframe/transforms_test.py +++ b/sdks/python/apache_beam/dataframe/transforms_test.py @@ -187,6 +187,15 @@ def test_idxmin_idxmax_with_empty_partition(self): self.run_scenario(df, lambda df: df[df.x > 5].idxmin()) self.run_scenario(df, lambda df: df[df.x > 5].idxmax()) + def test_min_max_skipna_false_with_empty_partition(self): + # run_scenario splits the input into two batches, and the filter leaves + # the second one empty. + df = pd.DataFrame({'x': [10.0, 1.0, 30.0, 2.0, 20.0]}) + self.run_scenario(df, lambda df: df[df.x > 5].x.min(skipna=False)) + self.run_scenario(df, lambda df: df[df.x > 5].x.max(skipna=False)) + self.run_scenario(df, lambda df: df[df.x > 5].min(skipna=False)) + self.run_scenario(df, lambda df: df[df.x > 5].max(skipna=False)) + def test_getitem_projection(self): df = pd.DataFrame({ 'Animal': ['Aardvark', 'Ant', 'Elephant', 'Zebra'],