diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 76ee21b4c9a50..0ea022e83ea08 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -720,6 +720,7 @@ Reshaping - Bug in :func:`pandas.cut` where large bins could incorrectly raise an error due to an integer overflow (:issue:`26045`) - Bug in :func:`DataFrame.sort_index` where an error is thrown when a multi-indexed ``DataFrame`` is sorted on all levels with the initial level sorted last (:issue:`26053`) - Bug in :meth:`Series.nlargest` treats ``True`` as smaller than ``False`` (:issue:`26154`) +- Bug in :func:`DataFrame.pivot_table` with a :class:`IntervalIndex` as pivot index would raise ``TypeError`` (:issue:`25814`) Sparse ^^^^^^ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index dc77599444505..c079b860bb924 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -181,7 +181,7 @@ def contains(cat, key, container): # can't be in container either. try: loc = cat.categories.get_loc(key) - except KeyError: + except (KeyError, TypeError): return False # loc is the location of key in categories, but also the *value* diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index cc91bef525eff..8543d2c2df7d6 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -19,6 +19,12 @@ def dropna(request): return request.param +@pytest.fixture(params=[([0] * 4, [1] * 4), (range(0, 3), range(1, 4))]) +def interval_values(request, closed): + left, right = request.param + return Categorical(pd.IntervalIndex.from_arrays(left, right, closed)) + + class TestPivotTable: def setup_method(self, method): @@ -198,6 +204,18 @@ def test_pivot_with_non_observable_dropna(self, dropna): tm.assert_frame_equal(result, expected) + def test_pivot_with_interval_index(self, interval_values, dropna): + # GH 25814 + df = DataFrame( + {'A': interval_values, + 'B': 1}) + result = df.pivot_table(index='A', values='B', dropna=dropna) + expected = DataFrame( + {'B': 1}, + index=Index(interval_values.unique(), + name='A')) + tm.assert_frame_equal(result, expected) + def test_pass_array(self): result = self.data.pivot_table( 'D', index=self.data.A, columns=self.data.C)