Skip to content

Commit d67222b

Browse files
gfyoungjorisvandenbossche
authored andcommitted
MAINT: More friendly error msg on Index overflow (#21377)
* MAINT: More useful error msg on Index overflow Display a more friendly error message when there is an OverflowError during Index construction. Partially addresses gh-15832. * DOC: Clarify how Index.__new__ handles dtype Partially addresses gh-15823. (cherry picked from commit defdb34)
1 parent 902cc4d commit d67222b

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

pandas/core/indexes/base.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,9 @@ class Index(IndexOpsMixin, PandasObject):
187187
----------
188188
data : array-like (1-dimensional)
189189
dtype : NumPy dtype (default: object)
190+
If dtype is None, we find the dtype that best fits the data.
191+
If an actual dtype is provided, we coerce to that dtype if it's safe.
192+
Otherwise, an error will be raised.
190193
copy : bool
191194
Make a copy of input ndarray
192195
name : object
@@ -312,7 +315,14 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
312315
if is_integer_dtype(dtype):
313316
inferred = lib.infer_dtype(data)
314317
if inferred == 'integer':
315-
data = np.array(data, copy=copy, dtype=dtype)
318+
try:
319+
data = np.array(data, copy=copy, dtype=dtype)
320+
except OverflowError:
321+
# gh-15823: a more user-friendly error message
322+
raise OverflowError(
323+
"the elements provided in the data cannot "
324+
"all be casted to the dtype {dtype}"
325+
.format(dtype=dtype))
316326
elif inferred in ['floating', 'mixed-integer-float']:
317327
if isna(data).any():
318328
raise ValueError('cannot convert float '

pandas/tests/indexes/test_base.py

+7
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,13 @@ def test_constructor_nonhashable_name(self, indices):
455455
tm.assert_raises_regex(TypeError, message,
456456
indices.set_names, names=renamed)
457457

458+
def test_constructor_overflow_int64(self):
459+
# see gh-15832
460+
msg = ("the elements provided in the data cannot "
461+
"all be casted to the dtype int64")
462+
with tm.assert_raises_regex(OverflowError, msg):
463+
Index([np.iinfo(np.uint64).max - 1], dtype="int64")
464+
458465
def test_view_with_args(self):
459466

460467
restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex',

0 commit comments

Comments
 (0)