Skip to content

Commit defdb34

Browse files
gfyoungjreback
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.
1 parent 879b15f commit defdb34

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
@@ -181,6 +181,9 @@ class Index(IndexOpsMixin, PandasObject):
181181
----------
182182
data : array-like (1-dimensional)
183183
dtype : NumPy dtype (default: object)
184+
If dtype is None, we find the dtype that best fits the data.
185+
If an actual dtype is provided, we coerce to that dtype if it's safe.
186+
Otherwise, an error will be raised.
184187
copy : bool
185188
Make a copy of input ndarray
186189
name : object
@@ -306,7 +309,14 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
306309
if is_integer_dtype(dtype):
307310
inferred = lib.infer_dtype(data)
308311
if inferred == 'integer':
309-
data = np.array(data, copy=copy, dtype=dtype)
312+
try:
313+
data = np.array(data, copy=copy, dtype=dtype)
314+
except OverflowError:
315+
# gh-15823: a more user-friendly error message
316+
raise OverflowError(
317+
"the elements provided in the data cannot "
318+
"all be casted to the dtype {dtype}"
319+
.format(dtype=dtype))
310320
elif inferred in ['floating', 'mixed-integer-float']:
311321
if isna(data).any():
312322
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)