Skip to content

Commit 5a3431f

Browse files
Khor Chean Weiyehoshuadimarsky
Khor Chean Wei
authored andcommitted
BUG Fix: pd.apply returns a dataframe when empty dataframe instead of a series (pandas-dev#47222)
* add test * add test * add * update rst
1 parent 12dca95 commit 5a3431f

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,7 @@ Conversion
854854
- Bug in metaclass of generic abstract dtypes causing :meth:`DataFrame.apply` and :meth:`Series.apply` to raise for the built-in function ``type`` (:issue:`46684`)
855855
- Bug in :meth:`DataFrame.to_records` returning inconsistent numpy types if the index was a :class:`MultiIndex` (:issue:`47263`)
856856
- Bug in :meth:`DataFrame.to_dict` for ``orient="list"`` or ``orient="index"`` was not returning native types (:issue:`46751`)
857+
- Bug in :meth:`DataFrame.apply` that returns a :class:`DataFrame` instead of a :class:`Series` when applied to an empty :class:`DataFrame` and ``axis=1`` (:issue:`39111`)
857858

858859
Strings
859860
^^^^^^^

pandas/core/apply.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -790,7 +790,10 @@ def apply_empty_result(self):
790790

791791
if not should_reduce:
792792
try:
793-
r = self.f(Series([], dtype=np.float64))
793+
if self.axis == 0:
794+
r = self.f(Series([], dtype=np.float64))
795+
else:
796+
r = self.f(Series(index=self.columns, dtype=np.float64))
794797
except Exception:
795798
pass
796799
else:

pandas/tests/apply/test_frame_apply.py

+8
Original file line numberDiff line numberDiff line change
@@ -1577,3 +1577,11 @@ def test_apply_type():
15771577
result = df.apply(type, axis=1)
15781578
expected = Series({"a": Series, "b": Series, "c": Series})
15791579
tm.assert_series_equal(result, expected)
1580+
1581+
1582+
def test_apply_on_empty_dataframe():
1583+
# GH 39111
1584+
df = DataFrame({"a": [1, 2], "b": [3, 0]})
1585+
result = df.head(0).apply(lambda x: max(x["a"], x["b"]), axis=1)
1586+
expected = Series([])
1587+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)