From 46bb47070901c64cb0bba8305564300aadadf3ee Mon Sep 17 00:00:00 2001 From: Brock Date: Fri, 8 Jan 2021 11:21:18 -0800 Subject: [PATCH] BUG: DataFrame.iloc.__setitem__ with IntegerArray values --- pandas/core/internals/blocks.py | 8 ++++++++ pandas/tests/indexing/test_iloc.py | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 94c7d325d0bc8..e4bb28c34dbe8 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -984,6 +984,14 @@ def setitem(self, indexer, value): values = values.astype(arr_value.dtype, copy=False) + elif is_ea_value: + # GH#38952 + if values.ndim == 1: + values[indexer] = value + else: + # TODO(EA2D): special case not needed with 2D EA + values[indexer] = value.to_numpy(values.dtype).reshape(-1, 1) + # set else: values[indexer] = value diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 24721a370241f..7dcb30efb8184 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -14,6 +14,7 @@ Index, NaT, Series, + array as pd_array, concat, date_range, isna, @@ -64,6 +65,24 @@ def test_iloc_getitem_list_int(self): class TestiLocBaseIndependent: """Tests Independent Of Base Class""" + @pytest.mark.parametrize("box", [pd_array, Series]) + def test_iloc_setitem_ea_inplace(self, frame_or_series, box): + # GH#38952 Case with not setting a full column + # IntegerArray without NAs + arr = pd_array([1, 2, 3, 4]) + obj = frame_or_series(arr.to_numpy("i8")) + values = obj.values + + obj.iloc[:2] = box(arr[2:]) + expected = frame_or_series(np.array([3, 4, 3, 4], dtype="i8")) + tm.assert_equal(obj, expected) + + # Check that we are actually in-place + if frame_or_series is Series: + assert obj.values is values + else: + assert obj.values.base is values.base and values.base is not None + def test_is_scalar_access(self): # GH#32085 index with duplicates doesnt matter for _is_scalar_access index = Index([1, 2, 1])