Skip to content

Backport PR #41974 on branch 1.3.x (BUG: UInt64Index.where with int64 value) #42036

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
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
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,8 @@ Numeric
- Bug in :meth:`Series.count` would result in an ``int32`` result on 32-bit platforms when argument ``level=None`` (:issue:`40908`)
- Bug in :class:`Series` and :class:`DataFrame` reductions with methods ``any`` and ``all`` not returning Boolean results for object data (:issue:`12863`, :issue:`35450`, :issue:`27709`)
- Bug in :meth:`Series.clip` would fail if the Series contains NA values and has nullable int or float as a data type (:issue:`40851`)
- Bug in :meth:`UInt64Index.where` and :meth:`UInt64Index.putmask` with an ``np.int64`` dtype ``other`` incorrectly raising ``TypeError`` (:issue:`41974`)


Conversion
^^^^^^^^^^
Expand Down
10 changes: 10 additions & 0 deletions pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,16 @@ class UInt64Index(IntegerIndex):
_default_dtype = np.dtype(np.uint64)
_dtype_validation_metadata = (is_unsigned_integer_dtype, "unsigned integer")

def _validate_fill_value(self, value):
# e.g. np.array([1]) we want np.array([1], dtype=np.uint64)
# see test_where_uin64
super()._validate_fill_value(value)
if hasattr(value, "dtype") and is_signed_integer_dtype(value.dtype):
if (value >= 0).all():
return value.astype(self.dtype)
raise TypeError
return value


class Float64Index(NumericIndex):
_index_descr_args = {
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/indexes/numeric/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,19 @@ def test_where(self, klass, index):
result = index.where(klass(cond))
tm.assert_index_equal(result, expected)

def test_where_uin64(self):
idx = UInt64Index([0, 6, 2])
mask = np.array([False, True, False])
other = np.array([1], dtype=np.int64)

expected = UInt64Index([1, 6, 1])

result = idx.where(mask, other)
tm.assert_index_equal(result, expected)

result = idx.putmask(~mask, other)
tm.assert_index_equal(result, expected)


class TestTake:
@pytest.mark.parametrize("klass", [Float64Index, Int64Index, UInt64Index])
Expand Down