diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 2e976371c0ac8..bd8b05b8de3e4 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -547,6 +547,7 @@ Reshaping - Bug in :func:`join` returned a non deterministic level-order for the resulting :class:`MultiIndex` (:issue:`36910`) - Bug in :meth:`DataFrame.combine_first()` caused wrong alignment with dtype ``string`` and one level of ``MultiIndex`` containing only ``NA`` (:issue:`37591`) - Fixed regression in :func:`merge` on merging DatetimeIndex with empty DataFrame (:issue:`36895`) +- Bug in :meth:`DataFrame.apply` not setting index of return value when ``func`` return type is ``dict`` (:issue:`37544`) Sparse ^^^^^^ diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 002e260742dc5..a14debce6eea7 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -362,8 +362,10 @@ def wrap_results_for_axis( isinstance(x, dict) for x in results.values() ): # Our operation was a to_dict op e.g. - # test_apply_dict GH#8735, test_apply_reduce_rows_to_dict GH#25196 - return self.obj._constructor_sliced(results) + # test_apply_dict GH#8735, test_apply_reduce_to_dict GH#25196 #37544 + res = self.obj._constructor_sliced(results) + res.index = res_index + return res try: result = self.obj._constructor(data=results) diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 03498b278f890..162035b53d68d 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -356,12 +356,17 @@ def test_apply_reduce_Series(self, float_frame): result = float_frame.apply(np.mean, axis=1) tm.assert_series_equal(result, expected) - def test_apply_reduce_rows_to_dict(self): - # GH 25196 - data = DataFrame([[1, 2], [3, 4]]) - expected = Series([{0: 1, 1: 3}, {0: 2, 1: 4}]) - result = data.apply(dict) - tm.assert_series_equal(result, expected) + def test_apply_reduce_to_dict(self): + # GH 25196 37544 + data = DataFrame([[1, 2], [3, 4]], columns=["c0", "c1"], index=["i0", "i1"]) + + result0 = data.apply(dict, axis=0) + expected0 = Series([{"i0": 1, "i1": 3}, {"i0": 2, "i1": 4}], index=data.columns) + tm.assert_series_equal(result0, expected0) + + result1 = data.apply(dict, axis=1) + expected1 = Series([{"c0": 1, "c1": 2}, {"c0": 3, "c1": 4}], index=data.index) + tm.assert_series_equal(result1, expected1) def test_apply_differently_indexed(self): df = DataFrame(np.random.randn(20, 10))