Skip to content

Commit

Permalink
BUG: NumericIndex should not support float16 dtype
Browse files Browse the repository at this point in the history
  • Loading branch information
Terji Petersen authored and Terji Petersen committed Nov 4, 2022
1 parent f6204a5 commit 06333da
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
11 changes: 9 additions & 2 deletions pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ class NumericIndex(Index):
Notes
-----
An NumericIndex instance can **only** contain numpy int64/32/16/8, uint64/32/16/8 or
float64/32/16 dtype. In particular, ``NumericIndex`` *can not* hold Pandas numeric
dtypes (:class:`Int64Dtype`, :class:`Int32Dtype` etc.).
float64/32 dtype. In particular, ``NumericIndex`` *can not* hold numpy float16
dtype or Pandas numeric dtypes (:class:`Int64Dtype`, :class:`Int32Dtype` etc.).
"""

_typ = "numericindex"
Expand Down Expand Up @@ -174,6 +174,10 @@ def _ensure_array(cls, data, dtype, copy: bool):
raise ValueError("Index data must be 1-dimensional")

subarr = np.asarray(subarr)
if subarr.dtype == "float16":
# float16 not supported (no indexing engine)
subarr = subarr.astype("float32")

return subarr

@classmethod
Expand All @@ -198,6 +202,9 @@ def _ensure_dtype(cls, dtype: Dtype | None) -> np.dtype | None:
return cls._default_dtype

dtype = pandas_dtype(dtype)
if dtype == np.float16:
# float16 not supported (no indexing engine)
dtype = np.dtype(np.float32)
assert isinstance(dtype, np.dtype)

if cls._is_backward_compat_public_numeric_index:
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/indexes/numeric/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,20 @@ def test_constructor_32bit(self, dtype):
assert index.dtype == np.int64


class TestFloat16Index:
# float 16 indexes not supported
# GH 49535
def test_array(self):
arr = np.array([1, 2, 3], dtype=np.float16)
result = NumericIndex(arr)

expected = NumericIndex([1, 2, 3], dtype=np.float32)
tm.assert_index_equal(result, expected, check_exact=True)

result = NumericIndex([1, 2, 3], dtype=np.float16)
tm.assert_index_equal(result, expected, check_exact=True)


class TestUIntNumericIndex(NumericInt):

_index_cls = NumericIndex
Expand Down

0 comments on commit 06333da

Please sign in to comment.