Skip to content

Commit 2d2606d

Browse files
peterpanmjTomAugspurger
authored andcommitted
BUG: fix IntervalIndex for pivot table raise type error (#26765)
1 parent a60888c commit 2d2606d

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v0.25.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -726,6 +726,7 @@ Reshaping
726726
- Bug in :func:`pandas.cut` where large bins could incorrectly raise an error due to an integer overflow (:issue:`26045`)
727727
- 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`)
728728
- Bug in :meth:`Series.nlargest` treats ``True`` as smaller than ``False`` (:issue:`26154`)
729+
- Bug in :func:`DataFrame.pivot_table` with a :class:`IntervalIndex` as pivot index would raise ``TypeError`` (:issue:`25814`)
729730

730731
Sparse
731732
^^^^^^

pandas/core/arrays/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def contains(cat, key, container):
181181
# can't be in container either.
182182
try:
183183
loc = cat.categories.get_loc(key)
184-
except KeyError:
184+
except (KeyError, TypeError):
185185
return False
186186

187187
# loc is the location of key in categories, but also the *value*

pandas/tests/reshape/test_pivot.py

+18
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ def dropna(request):
1919
return request.param
2020

2121

22+
@pytest.fixture(params=[([0] * 4, [1] * 4), (range(0, 3), range(1, 4))])
23+
def interval_values(request, closed):
24+
left, right = request.param
25+
return Categorical(pd.IntervalIndex.from_arrays(left, right, closed))
26+
27+
2228
class TestPivotTable:
2329

2430
def setup_method(self, method):
@@ -198,6 +204,18 @@ def test_pivot_with_non_observable_dropna(self, dropna):
198204

199205
tm.assert_frame_equal(result, expected)
200206

207+
def test_pivot_with_interval_index(self, interval_values, dropna):
208+
# GH 25814
209+
df = DataFrame(
210+
{'A': interval_values,
211+
'B': 1})
212+
result = df.pivot_table(index='A', values='B', dropna=dropna)
213+
expected = DataFrame(
214+
{'B': 1},
215+
index=Index(interval_values.unique(),
216+
name='A'))
217+
tm.assert_frame_equal(result, expected)
218+
201219
def test_pass_array(self):
202220
result = self.data.pivot_table(
203221
'D', index=self.data.A, columns=self.data.C)

0 commit comments

Comments
 (0)