Skip to content

REGR: preserve Int32 dtype on setitem #42166

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

Merged
merged 1 commit into from
Jun 21, 2021
Merged
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
21 changes: 20 additions & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,12 @@
isna,
)

from pandas.core import algorithms as algos
import pandas.core.common as com
from pandas.core.construction import array as pd_array
from pandas.core.construction import (
array as pd_array,
extract_array,
)
from pandas.core.indexers import (
check_array_indexer,
is_empty_indexer,
Expand Down Expand Up @@ -1660,6 +1664,21 @@ def _setitem_with_indexer(self, indexer, value, name="iloc"):
if com.is_null_slice(indexer[0]):
# We are setting an entire column
self.obj[key] = value
return
elif is_array_like(value):
Copy link
Contributor

Choose a reason for hiding this comment

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

this is getting super messy, but i guess ok

# GH#42099
arr = extract_array(value, extract_numpy=True)
taker = -1 * np.ones(len(self.obj), dtype=np.intp)
empty_value = algos.take_nd(arr, taker)
if not isinstance(value, ABCSeries):
# if not Series (in which case we need to align),
# we can short-circuit
empty_value[indexer[0]] = arr
self.obj[key] = empty_value
return

self.obj[key] = empty_value

else:
self.obj[key] = infer_fill_value(value)

Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1830,6 +1830,23 @@ def test_loc_setitem_with_expansion_nonunique_index(self, index, request):
)
tm.assert_frame_equal(df, expected)

@pytest.mark.parametrize(
"dtype", ["Int32", "Int64", "UInt32", "UInt64", "Float32", "Float64"]
)
def test_loc_setitem_with_expansion_preserves_nullable_int(self, dtype):
# GH#42099
ser = Series([0, 1, 2, 3], dtype=dtype)
df = DataFrame({"data": ser})

result = DataFrame(index=df.index)
result.loc[df.index, "data"] = ser

tm.assert_frame_equal(result, df)

result = DataFrame(index=df.index)
result.loc[df.index, "data"] = ser._values
tm.assert_frame_equal(result, df)


class TestLocCallable:
def test_frame_loc_getitem_callable(self):
Expand Down