Skip to content

Commit 6db0b55

Browse files
REGR: fix transform of empty DataFrame/Series (#39639)
1 parent d558bce commit 6db0b55

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/source/whatsnew/v1.2.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Fixed regressions
2121
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
2222
- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
2323
- Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`)
24+
- Fixed regression in :meth:`DataFrame.transform` failing in case of an empty DataFrame or Series (:issue:`39636`)
2425
- Fixed regression in :meth:`core.window.rolling.Rolling.count` where the ``min_periods`` argument would be set to ``0`` after the operation (:issue:`39554`)
2526
-
2627

pandas/core/aggregation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,7 @@ def transform(
457457

458458
# Functions that transform may return empty Series/DataFrame
459459
# when the dtype is not appropriate
460-
if isinstance(result, (ABCSeries, ABCDataFrame)) and result.empty:
460+
if isinstance(result, (ABCSeries, ABCDataFrame)) and result.empty and not obj.empty:
461461
raise ValueError("Transform function failed")
462462
if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals(
463463
obj.index

pandas/tests/apply/test_frame_transform.py

+10
Original file line numberDiff line numberDiff line change
@@ -274,3 +274,13 @@ def test_transform_mixed_column_name_dtypes():
274274
msg = r"Column\(s\) \[1, 'b'\] do not exist"
275275
with pytest.raises(SpecificationError, match=msg):
276276
df.transform({"a": int, 1: str, "b": int})
277+
278+
279+
def test_transform_empty_dataframe():
280+
# https://github.com/pandas-dev/pandas/issues/39636
281+
df = DataFrame([], columns=["col1", "col2"])
282+
result = df.transform(lambda x: x + 10)
283+
tm.assert_frame_equal(result, df)
284+
285+
result = df["col1"].transform(lambda x: x + 10)
286+
tm.assert_series_equal(result, df["col1"])

0 commit comments

Comments
 (0)