Skip to content

Commit

Permalink
Backport PR #54699 on branch 2.1.x (BUG: setitem with object type ins…
Browse files Browse the repository at this point in the history
…erting Series maintains Series) (#54760)

Backport PR #54699: BUG: setitem with object type inserting Series maintains Series

Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and mroeschke committed Aug 25, 2023
1 parent 4f66163 commit b761844
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,7 @@ Indexing
- Bug in :meth:`DataFrame.__setitem__` losing dtype when setting a :class:`DataFrame` into duplicated columns (:issue:`53143`)
- Bug in :meth:`DataFrame.__setitem__` with a boolean mask and :meth:`DataFrame.putmask` with mixed non-numeric dtypes and a value other than ``NaN`` incorrectly raising ``TypeError`` (:issue:`53291`)
- Bug in :meth:`DataFrame.iloc` when using ``nan`` as the only element (:issue:`52234`)
- Bug in :meth:`Series.loc` casting :class:`Series` to ``np.dnarray`` when assigning :class:`Series` at predefined index of ``object`` dtype :class:`Series` (:issue:`48933`)

Missing
^^^^^^^
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1133,7 +1133,9 @@ def setitem(self, indexer, value, using_cow: bool = False) -> Block:
# length checking
check_setitem_lengths(indexer, value, values)

value = extract_array(value, extract_numpy=True)
if self.dtype != _dtype_obj:
# GH48933: extract_array would convert a pd.Series value to np.ndarray
value = extract_array(value, extract_numpy=True)
try:
casted = np_can_hold_element(values.dtype, value)
except LossySetitemError:
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1132,3 +1132,19 @@ def test_scalar_setitem_series_with_nested_value_length1(value, indexer_sli):
assert (ser.loc[0] == value).all()
else:
assert ser.loc[0] == value


def test_object_dtype_series_set_series_element():
# GH 48933
s1 = Series(dtype="O", index=["a", "b"])

s1["a"] = Series()
s1.loc["b"] = Series()

tm.assert_series_equal(s1.loc["a"], Series())
tm.assert_series_equal(s1.loc["b"], Series())

s2 = Series(dtype="O", index=["a", "b"])

s2.iloc[1] = Series()
tm.assert_series_equal(s2.iloc[1], Series())

0 comments on commit b761844

Please sign in to comment.