Skip to content

Backport PR #54699 on branch 2.1.x (BUG: setitem with object type inserting Series maintains Series) #54760

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
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
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())