Skip to content

BUG FIX: incorrect type when casting to nullable type in multiindex dataframe #47419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -11917,6 +11917,11 @@ def _reindex_for_setitem(value: DataFrame | Series, index: Index) -> ArrayLike:
# reindex if necessary

if value.index.equals(index) or not len(index):
if isinstance(value, DataFrame):
dtype_list = value.dtypes.unique()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should use find_common_type

if len(dtype_list) == 1:
dtype = dtype_list[0].name.lower()
return value._values.astype(dtype).copy()
return value._values.copy()

# GH#4107
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/indexing/multiindex/test_multiindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should use any_signed_int_ea_dtype

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)