Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
38 changes: 34 additions & 4 deletions sdks/python/apache_beam/dataframe/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions sdks/python/apache_beam/dataframe/frames_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
9 changes: 9 additions & 0 deletions sdks/python/apache_beam/dataframe/transforms_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
Loading