Skip to content
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

REGR: setitem writing into RangeIndex instead of creating a copy #47143

Merged
merged 5 commits into from
Jun 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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/v1.4.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`DataFrame.replace` when the replacement value was explicitly ``None`` when passed in a dictionary to ``to_replace`` also casting other columns to object dtype even when there were no values to replace (:issue:`46634`)
- Fixed regression in :meth:`DataFrame.loc.__setitem__` updating :class:`RangeIndex` when index was set as new column and column was updated afterwards (:issue:`47128`)
- Fixed regression in :meth:`DataFrame.nsmallest` led to wrong results when ``np.nan`` in the sorting column (:issue:`46589`)
- Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`)
- Fixed regression in :meth:`.Groupby.transform` and :meth:`.Groupby.agg` failing with ``engine="numba"`` when the index was a :class:`MultiIndex` (:issue:`46867`)
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ def sanitize_array(
dtype = dtype.numpy_dtype

# extract ndarray or ExtensionArray, ensure we have no PandasArray
data = extract_array(data, extract_numpy=True)
data = extract_array(data, extract_numpy=True, extract_range=True)

if isinstance(data, np.ndarray) and data.ndim == 0:
if dtype is None:
Expand Down Expand Up @@ -611,6 +611,8 @@ def sanitize_array(
if hasattr(data, "__array__"):
# e.g. dask array GH#38645
data = np.asarray(data)
if copy:
data = np.copy(data)
else:
data = list(data)

Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/frame/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,15 @@ def test_frame_setitem_newcol_timestamp(self):
data[ts] = np.nan # works, mostly a smoke-test
assert np.isnan(data[ts]).all()

def test_frame_setitem_rangeindex_into_new_col(self):
# GH#47128
df = DataFrame({"a": ["a", "b"]})
df["b"] = df.index
df.loc[[False, True], "b"] = 100
result = df.loc[[1], :]
expected = DataFrame({"a": ["b"], "b": [100]}, index=[1])
tm.assert_frame_equal(result, expected)


class TestDataFrameSetItemSlicing:
def test_setitem_slice_position(self):
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/test_downstream.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,3 +304,28 @@ def test_missing_required_dependency():
output = exc.value.stdout.decode()
for name in ["numpy", "pytz", "dateutil"]:
assert name in output


def test_frame_setitem_dask_array_into_new_col():
# GH#47128

# dask sets "compute.use_numexpr" to False, so catch the current value
# and ensure to reset it afterwards to avoid impacting other tests
olduse = pd.get_option("compute.use_numexpr")

try:
toolz = import_module("toolz") # noqa:F841
dask = import_module("dask") # noqa:F841

import dask.array as da

dda = da.array([1, 2])
df = DataFrame({"a": ["a", "b"]})
df["b"] = dda
df["c"] = dda
df.loc[[False, True], "b"] = 100
result = df.loc[[1], :]
expected = DataFrame({"a": ["b"], "b": [100], "c": [2]}, index=[1])
tm.assert_frame_equal(result, expected)
finally:
pd.set_option("compute.use_numexpr", olduse)