Skip to content

Commit 12016fe

Browse files
committed
MAINT: More useful error msg on Index overflow
Display a more friendly error message when there is an OverflowError during Index construction. Partially addresses pandas-devgh-15832.
1 parent 4807905 commit 12016fe

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

pandas/core/indexes/base.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,14 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
306306
if is_integer_dtype(dtype):
307307
inferred = lib.infer_dtype(data)
308308
if inferred == 'integer':
309-
data = np.array(data, copy=copy, dtype=dtype)
309+
try:
310+
data = np.array(data, copy=copy, dtype=dtype)
311+
except OverflowError:
312+
# gh-15823: a more user-friendly error message
313+
raise OverflowError(
314+
"the elements provided in the data cannot "
315+
"all be casted to the dtype {dtype}"
316+
.format(dtype=dtype))
310317
elif inferred in ['floating', 'mixed-integer-float']:
311318
if isna(data).any():
312319
raise ValueError('cannot convert float '

pandas/tests/indexes/test_base.py

+7
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,13 @@ def test_constructor_nonhashable_name(self, indices):
474474
tm.assert_raises_regex(TypeError, message,
475475
indices.set_names, names=renamed)
476476

477+
def test_constructor_overflow_int64(self):
478+
# see gh-15832
479+
msg = ("the elements provided in the data cannot "
480+
"all be casted to the dtype int64")
481+
with tm.assert_raises_regex(OverflowError, msg):
482+
Index([np.iinfo(np.uint64).max - 1], dtype="int64")
483+
477484
def test_view_with_args(self):
478485

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

0 commit comments

Comments
 (0)