From eb2983965a3e8f919d3a33f9ce4e28d21cd609a4 Mon Sep 17 00:00:00 2001 From: MeeseeksMachine <39504233+meeseeksmachine@users.noreply.github.com> Date: Fri, 23 Sep 2022 22:05:48 +0200 Subject: [PATCH] Backport PR #48713 on branch 1.5.x (BUG: pivot_table raising Future Warning with datetime column as index) (#48742) Backport PR #48713: BUG: pivot_table raising Future Warning with datetime column as index Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com> --- doc/source/whatsnew/v1.5.1.rst | 1 + pandas/core/reshape/pivot.py | 2 +- pandas/tests/reshape/test_pivot.py | 32 ++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.5.1.rst b/doc/source/whatsnew/v1.5.1.rst index 0f71814341aba..209548a4adaf9 100644 --- a/doc/source/whatsnew/v1.5.1.rst +++ b/doc/source/whatsnew/v1.5.1.rst @@ -27,6 +27,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Bug in :meth:`DataFrame.to_hdf` raising ``AssertionError`` with boolean index (:issue:`48667`) +- Bug in :meth:`DataFrame.pivot_table` raising unexpected ``FutureWarning`` when setting datetime column as index (:issue:`48683`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index b4a2b8d0e52f4..66a3425d0d398 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -318,7 +318,7 @@ def _add_margins( from pandas import DataFrame - margin_dummy = DataFrame(row_margin, columns=[key]).T + margin_dummy = DataFrame(row_margin, columns=Index([key])).T row_names = result.index.names # check the result column and leave floats diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 30859e9fdafc0..77a43954cf699 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2237,6 +2237,38 @@ def test_pivot_ea_dtype_dropna(self, dropna): ) tm.assert_frame_equal(result, expected) + def test_pivot_table_datetime_warning(self): + # GH#48683 + df = DataFrame( + { + "a": "A", + "b": [1, 2], + "date": pd.Timestamp("2019-12-31"), + "sales": [10.0, 11], + } + ) + with tm.assert_produces_warning(None): + result = df.pivot_table( + index=["b", "date"], columns="a", margins=True, aggfunc="sum" + ) + expected = DataFrame( + [[10.0, 10.0], [11.0, 11.0], [21.0, 21.0]], + index=MultiIndex.from_arrays( + [ + Index([1, 2, "All"], name="b"), + Index( + [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31"), ""], + dtype=object, + name="date", + ), + ] + ), + columns=MultiIndex.from_tuples( + [("sales", "A"), ("sales", "All")], names=[None, "a"] + ), + ) + tm.assert_frame_equal(result, expected) + class TestPivot: def test_pivot(self):