Skip to content

Commit

Permalink
REGR: preserve Int32 dtype on setitem (#42166)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored Jun 21, 2021
1 parent d01062e commit 6ca8757
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
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):
# 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

0 comments on commit 6ca8757

Please sign in to comment.