Skip to content

REGR: Fix assignment bug for unary operators #39971

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 6 commits into from
Feb 23, 2021
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/v1.2.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~

- Fixed regression in :meth:`~DataFrame.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`)
- Fixed regression in :class:`IntegerArray` unary ops propagating mask on assignment (:issue:`39943`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For future reference, I think we should generally say something like "nullable integer dtype" instead of "IntegerArray", as most users should never deal / know about IntegerArray

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid point, I can update this

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done. #40019. thanks @dsaxton

- Fixed regression in :meth:`DataFrame.__setitem__` not aligning :class:`DataFrame` on right-hand side for boolean indexer (:issue:`39931`)

.. ---------------------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,13 +316,13 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False):
super().__init__(values, mask, copy=copy)

def __neg__(self):
return type(self)(-self._data, self._mask)
return type(self)(-self._data, self._mask.copy())

def __pos__(self):
return self
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should do the same for __pos__?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably not for a backport. but indeed this needs some discussion to ensure consistency across the codebase. see TimedeltaArray

    def __pos__(self) -> TimedeltaArray:
        return type(self)(self._data, freq=self.freq)
>>> import pandas as pd
>>> pd.__version__
'1.3.0.dev0+804.g3289f82975'
>>>
>>> arr = pd.timedelta_range(0, periods=10)._values
>>> arr
<TimedeltaArray>
['0 days', '1 days', '2 days', '3 days', '4 days', '5 days', '6 days',
 '7 days', '8 days', '9 days']
Length: 10, dtype: timedelta64[ns]
>>>
>>> arr2 = +arr
>>>
>>> arr2 is arr
False
>>>
>>> arr2._data is arr._data
True
>>>
>>> arr2[5] = None
>>>
>>> arr
<TimedeltaArray>
['0 days', '1 days', '2 days', '3 days', '4 days',      NaT, '6 days',
 '7 days', '8 days', '9 days']
Length: 10, dtype: timedelta64[ns]
>>>
>>>

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I see, so that's indeed something we should fix more generally. Is there already an issue about it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the context here I had been thinking that something like s1 = +s should behave the same way as s1 = s, but actually I think you are right. Likely +s should return something new instead of simply a reference to the thing.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there already an issue about it?

no. will need to create one, since the issue that this PR addresses is slightly different. #39943 is about different arrays sharing a mask, whereas returning self for __pos__, although maybe incorrect, does not create the inconsistencies when assigning null and non-null vales


def __abs__(self):
return type(self)(np.abs(self._data), self._mask)
return type(self)(np.abs(self._data), self._mask.copy())

@classmethod
def _from_sequence(
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/masked.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def __len__(self) -> int:
return len(self._data)

def __invert__(self: BaseMaskedArrayT) -> BaseMaskedArrayT:
return type(self)(~self._data, self._mask)
return type(self)(~self._data, self._mask.copy())

def to_numpy(
self,
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/arrays/masked/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,16 @@ def test_error_len_mismatch(data, all_arithmetic_operators):
s = pd.Series(data)
with pytest.raises(ValueError, match="Lengths must match"):
op(s, other)


@pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"])
@pytest.mark.parametrize(
"values, dtype", [([1, 2, 3], "Int64"), ([True, False, True], "boolean")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can use the data fixture here as used in the other tests above

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is being addressed in #39916, so no action required here

)
def test_unary_op_does_not_propagate_mask(op, values, dtype):
# https://github.com/pandas-dev/pandas/issues/39943
s = pd.Series(values, dtype=dtype)
result = getattr(s, op)()
expected = result.copy(deep=True)
s[0] = None
tm.assert_series_equal(result, expected)