|
11 | 11 |
|
12 | 12 | import pandas.hashtable as _hash
|
13 | 13 | from pandas import compat, lib, algos, tslib
|
| 14 | +from pandas.compat.numpy import _np_version_under1p10 |
14 | 15 | from pandas.types.common import (_ensure_int64, _ensure_object,
|
15 | 16 | _ensure_float64, _get_dtype,
|
16 | 17 | is_float, is_scalar,
|
@@ -829,9 +830,37 @@ def _checked_add_with_arr(arr, b):
|
829 | 830 |
|
830 | 831 | Raises
|
831 | 832 | ------
|
832 |
| - OverflowError if any x + y exceeds the maximum int64 value. |
| 833 | + OverflowError if any x + y exceeds the maximum or minimum int64 value. |
833 | 834 | """
|
834 |
| - if (np.iinfo(np.int64).max - b < arr).any(): |
835 |
| - raise OverflowError("Python int too large to " |
836 |
| - "convert to C long") |
| 835 | + # For performance reasons, we broadcast 'b' to the new array 'b2' |
| 836 | + # so that it has the same size as 'arr'. |
| 837 | + if _np_version_under1p10: |
| 838 | + if lib.isscalar(b): |
| 839 | + b2 = np.empty(arr.shape) |
| 840 | + b2.fill(b) |
| 841 | + else: |
| 842 | + b2 = b |
| 843 | + else: |
| 844 | + b2 = np.broadcast_to(b, arr.shape) |
| 845 | + |
| 846 | + # gh-14324: For each element in 'arr' and its corresponding element |
| 847 | + # in 'b2', we check the sign of the element in 'b2'. If it is positive, |
| 848 | + # we then check whether its sum with the element in 'arr' exceeds |
| 849 | + # np.iinfo(np.int64).max. If so, we have an overflow error. If it |
| 850 | + # it is negative, we then check whether its sum with the element in |
| 851 | + # 'arr' exceeds np.iinfo(np.int64).min. If so, we have an overflow |
| 852 | + # error as well. |
| 853 | + mask1 = b2 > 0 |
| 854 | + mask2 = b2 < 0 |
| 855 | + |
| 856 | + if not mask1.any(): |
| 857 | + to_raise = (np.iinfo(np.int64).min - b2 > arr).any() |
| 858 | + elif not mask2.any(): |
| 859 | + to_raise = (np.iinfo(np.int64).max - b2 < arr).any() |
| 860 | + else: |
| 861 | + to_raise = ((np.iinfo(np.int64).max - b2[mask1] < arr[mask1]).any() or |
| 862 | + (np.iinfo(np.int64).min - b2[mask2] > arr[mask2]).any()) |
| 863 | + |
| 864 | + if to_raise: |
| 865 | + raise OverflowError("Overflow in int64 addition") |
837 | 866 | return arr + b
|
0 commit comments