MAINT: More friendly error msg on Index overflow (#21377) · pandas-dev/pandas@defdb34 (original) (raw)

2 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -181,6 +181,9 @@ class Index(IndexOpsMixin, PandasObject):
181 181 ----------
182 182 data : array-like (1-dimensional)
183 183 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.
184 187 copy : bool
185 188 Make a copy of input ndarray
186 189 name : object
@@ -306,7 +309,14 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
306 309 if is_integer_dtype(dtype):
307 310 inferred = lib.infer_dtype(data)
308 311 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))
310 320 elif inferred in ['floating', 'mixed-integer-float']:
311 321 if isna(data).any():
312 322 raise ValueError('cannot convert float '
Original file line number Diff line number Diff line change
@@ -474,6 +474,13 @@ def test_constructor_nonhashable_name(self, indices):
474 474 tm.assert_raises_regex(TypeError, message,
475 475 indices.set_names, names=renamed)
476 476
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 +
477 484 def test_view_with_args(self):
478 485
479 486 restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex',