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
24 changes: 24 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ def dropna(request):
return request.param


@pytest.fixture(
params=[
pd.Categorical([pd.Interval(0, 1, 'right')] * 4),
pd.Categorical([pd.Interval(0, 1, 'left')] * 4),
pd.Categorical([pd.Interval(low, high, 'right')
for low, high in zip(range(0, 3), range(1, 4))]),
pd.Categorical([pd.Interval(low, high, 'left')
for low, high in zip(range(0, 3), range(1, 4))])])
def interval_values(request):
return request.param


class TestPivotTable:

def setup_method(self, method):
Expand Down Expand Up @@ -198,6 +210,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 = pd.DataFrame(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add the issue number as a comment

{'A': interval_values,
'B': [1] * interval_values.size})
result = df.pivot_table(index='A', values='B', dropna=dropna)
expected = pd.DataFrame(
{'B': [1]},
index=pd.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