Skip to content

BUG: fix IntervalIndex for pivot table raise type error #26765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jun 13, 2019
Merged
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Bug Fixes

- Bug in :meth:`~pandas.core.groupby.GroupBy.transform` where applying a function to a timezone aware column would return a timezone naive result (:issue:`24198`)
- Bug in :func:`DataFrame.join` when joining on a timezone aware :class:`DatetimeIndex` (:issue:`23931`)
- Bug in :func:`DataFrame.pivot_table` where use :class:`IntervalIndex` as pivot index would raise ``TypeError`` (:issue:`25814`)

**Visualization**

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -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*
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ def dropna(request):
return request.param


@pytest.fixture(params=['right', 'left'])
def closed(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):
Expand Down Expand Up @@ -198,6 +209,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)
Expand Down