From 3689528a578484ce343c0db9bffbae71a590e5d5 Mon Sep 17 00:00:00 2001 From: weikhor Date: Sun, 19 Jun 2022 21:13:05 +0800 Subject: [PATCH 1/3] add --- pandas/core/frame.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 39a940169e1f3..b4244fd9a123b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11512,6 +11512,10 @@ def _reindex_for_setitem(value: DataFrame | Series, index: Index) -> ArrayLike: # reindex if necessary if value.index.equals(index) or not len(index): + dtype_list = value.dtypes.unique() + if len(dtype_list) == 1: + dtype = dtype_list[0].name.lower() + return value._values.astype(dtype).copy() return value._values.copy() # GH#4107 From 8cf01ef24bf7a7b83539d64094f16fc86d3ec731 Mon Sep 17 00:00:00 2001 From: weikhor Date: Sun, 31 Jul 2022 19:11:26 +0800 Subject: [PATCH 2/3] add dataframe --- pandas/core/frame.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a90826f7960dc..8dce36849b3d2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11918,10 +11918,11 @@ def _reindex_for_setitem(value: DataFrame | Series, index: Index) -> ArrayLike: # reindex if necessary if value.index.equals(index) or not len(index): - dtype_list = value.dtypes.unique() - if len(dtype_list) == 1: - dtype = dtype_list[0].name.lower() - return value._values.astype(dtype).copy() + if isinstance(value, DataFrame): + dtype_list = value.dtypes.unique() + if len(dtype_list) == 1: + dtype = dtype_list[0].name.lower() + return value._values.astype(dtype).copy() return value._values.copy() # GH#4107 From 5323e09a132840053a931456e5f6ec7be4d14097 Mon Sep 17 00:00:00 2001 From: weikhor Date: Mon, 1 Aug 2022 13:41:43 +0800 Subject: [PATCH 3/3] add test --- .../tests/indexing/multiindex/test_multiindex.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py index 08e15545cb998..bf74a52e81dd3 100644 --- a/pandas/tests/indexing/multiindex/test_multiindex.py +++ b/pandas/tests/indexing/multiindex/test_multiindex.py @@ -227,3 +227,17 @@ def test_multiindex_repeated_keys(self): ], Series([1, 1, 2, 2], MultiIndex.from_arrays([["a", "a", "b", "b"]])), ) + + @pytest.mark.parametrize("data_type", ["int64", "int32", "float64", "float32"]) + def test_multiindex_dataframe_incorrect_type(self, data_type): + # GH 46896 + df = DataFrame( + columns=MultiIndex.from_tuples([("a", "c"), ("a", "d")]), + data=[[1, 2], [3, 4]], + ) + df["a"] = df["a"].astype(data_type) + + result = df.dtypes + expected = Series(data=[data_type, data_type], index=[["a", "a"], ["c", "d"]]) + + tm.assert_series_equal(result, expected)