Skip to content

[BUG] Validate dtype when Int64Index, UInt64Index, or Float64Index are cons… #29545

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 9 commits into from
Nov 18, 2019
17 changes: 16 additions & 1 deletion pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
is_float_dtype,
is_integer_dtype,
is_scalar,
is_signed_integer_dtype,
is_unsigned_integer_dtype,
needs_i8_conversion,
pandas_dtype,
)
Expand Down Expand Up @@ -45,7 +47,7 @@ class NumericIndex(Index):
_is_numeric_dtype = True

def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None):

cls._validate_dtype(cls, dtype)
if fastpath is not None:
warnings.warn(
"The 'fastpath' keyword is deprecated, and will be "
Expand All @@ -72,6 +74,19 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None):
name = data.name
return cls._simple_new(subarr, name=name)

def _validate_dtype(cls, dtype):
if not dtype:
return
if cls._typ == "int64index":
if not is_signed_integer_dtype(dtype):
raise ValueError("Incorrect `dtype` passed")
elif cls._typ == "uint64index":
if not is_unsigned_integer_dtype(dtype):
raise ValueError("Incorrect `dtype` passed")
elif cls._typ == "float64index":
if not is_float_dtype(dtype):
raise ValueError("Incorrect `dtype` passed")

@Appender(_index_shared_docs["_maybe_cast_slice_bound"])
def _maybe_cast_slice_bound(self, label, side, kind):
assert kind in ["ix", "loc", "getitem", None]
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/indexes/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,18 @@ def test_constructor(self):
result = Index(np.array([np.nan]))
assert pd.isna(result.values).all()

@pytest.mark.parametrize(
"index, dtype",
[
(pd.Int64Index, "float64"),
(pd.UInt64Index, "categorical"),
(pd.Float64Index, "datetime64"),
],
)
def test_invalid_dtype(self, index, dtype):
with pytest.raises(ValueError):
index([1, 2, 3], dtype=dtype)

def test_constructor_invalid(self):

# invalid
Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/series/indexing/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ def test_get():
1764.0,
1849.0,
1936.0,
],
dtype="object",
]
),
)

Expand Down