diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 740a0f888d38f..c19352af406a8 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -852,6 +852,7 @@ Conversion - 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`) - Bug in :meth:`DataFrame.to_records` returning inconsistent numpy types if the index was a :class:`MultiIndex` (:issue:`47263`) - Bug in :meth:`DataFrame.to_dict` for ``orient="list"`` or ``orient="index"`` was not returning native types (:issue:`46751`) +- 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`) Strings ^^^^^^^ diff --git a/pandas/core/apply.py b/pandas/core/apply.py index c0200c7d7c5b7..18a0f9b7aa2ce 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -790,7 +790,10 @@ def apply_empty_result(self): if not should_reduce: try: - r = self.f(Series([], dtype=np.float64)) + if self.axis == 0: + r = self.f(Series([], dtype=np.float64)) + else: + r = self.f(Series(index=self.columns, dtype=np.float64)) except Exception: pass else: diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index ef7ab4a469865..72a9d8723d34c 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -1577,3 +1577,11 @@ def test_apply_type(): result = df.apply(type, axis=1) expected = Series({"a": Series, "b": Series, "c": Series}) tm.assert_series_equal(result, expected) + + +def test_apply_on_empty_dataframe(): + # GH 39111 + df = DataFrame({"a": [1, 2], "b": [3, 0]}) + result = df.head(0).apply(lambda x: max(x["a"], x["b"]), axis=1) + expected = Series([]) + tm.assert_series_equal(result, expected)