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.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^
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
18 changes: 18 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down