From 244a90b9c3192eb0f053745c1c8483991496c133 Mon Sep 17 00:00:00 2001 From: jschendel Date: Mon, 17 Dec 2018 18:21:38 -0700 Subject: [PATCH] ERR: Improve error message for cut with infinity and integer bins --- pandas/core/reshape/tile.py | 6 +++++- pandas/tests/reshape/test_cut.py | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 5d5f6cf8102be..f8e917a1a8688 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -205,7 +205,11 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3, rng = (nanops.nanmin(x), nanops.nanmax(x)) mn, mx = [mi + 0.0 for mi in rng] - if mn == mx: # adjust end points before binning + if np.isinf(mn) or np.isinf(mx): + # GH 24314 + raise ValueError('cannot specify integer `bins` when input data ' + 'contains infinity') + elif mn == mx: # adjust end points before binning mn -= .001 * abs(mn) if mn != 0 else .001 mx += .001 * abs(mx) if mx != 0 else .001 bins = np.linspace(mn, mx, bins + 1, endpoint=True) diff --git a/pandas/tests/reshape/test_cut.py b/pandas/tests/reshape/test_cut.py index 458b4b13248dd..6833460fa515b 100644 --- a/pandas/tests/reshape/test_cut.py +++ b/pandas/tests/reshape/test_cut.py @@ -137,6 +137,17 @@ def test_cut_not_1d_arg(arg, cut_func): cut_func(arg, 2) +@pytest.mark.parametrize('data', [ + [0, 1, 2, 3, 4, np.inf], + [-np.inf, 0, 1, 2, 3, 4], + [-np.inf, 0, 1, 2, 3, 4, np.inf]]) +def test_int_bins_with_inf(data): + # GH 24314 + msg = 'cannot specify integer `bins` when input data contains infinity' + with pytest.raises(ValueError, match=msg): + cut(data, bins=3) + + def test_cut_out_of_range_more(): # see gh-1511 name = "x"