Skip to content

Commit 234edac

Browse files
jorisvandenbosschesimonjayhawkins
authored andcommitted
Backport PR pandas-dev#39639: REGR: fix transform of empty DataFrame/Series
1 parent 75f9bb8 commit 234edac

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
@@ -456,7 +456,7 @@ def transform(
456456

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

pandas/tests/frame/apply/test_frame_transform.py

+10
Original file line numberDiff line numberDiff line change
@@ -258,3 +258,13 @@ def test_transform_missing_columns(axis):
258258
match = re.escape("Column(s) ['C'] do not exist")
259259
with pytest.raises(SpecificationError, match=match):
260260
df.transform({"C": "cumsum"})
261+
262+
263+
def test_transform_empty_dataframe():
264+
# https://github.com/pandas-dev/pandas/issues/39636
265+
df = DataFrame([], columns=["col1", "col2"])
266+
result = df.transform(lambda x: x + 10)
267+
tm.assert_frame_equal(result, df)
268+
269+
result = df["col1"].transform(lambda x: x + 10)
270+
tm.assert_series_equal(result, df["col1"])

0 commit comments

Comments
 (0)