Skip to content

Commit f2b0bdc

Browse files
mroeschkegfyoung
authored andcommitted
BUG: Allow Series with same name with crosstab (#16028)
Closes gh-13279
1 parent 6b8e436 commit f2b0bdc

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ Reshaping
312312
- Bug when using :func:`isin` on a large object series and large comparison array (:issue:`16012`)
313313
- Fixes regression from 0.20, :func:`Series.aggregate` and :func:`DataFrame.aggregate` allow dictionaries as return values again (:issue:`16741`)
314314
- Fixes dtype of result with integer dtype input, from :func:`pivot_table` when called with ``margins=True`` (:issue:`17013`)
315+
- Bug in ``pd.crosstab()`` where passing two ``Series`` with the same name raised a ``KeyError`` (:issue:`13279`)
315316

316317
Numeric
317318
^^^^^^^

pandas/core/reshape/pivot.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,17 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
148148

149149
table = agged
150150
if table.index.nlevels > 1:
151-
to_unstack = [agged.index.names[i] or i
152-
for i in range(len(index), len(keys))]
151+
# Related GH #17123
152+
# If index_names are integers, determine whether the integers refer
153+
# to the level position or name.
154+
index_names = agged.index.names[:len(index)]
155+
to_unstack = []
156+
for i in range(len(index), len(keys)):
157+
name = agged.index.names[i]
158+
if name is None or name in index_names:
159+
to_unstack.append(i)
160+
else:
161+
to_unstack.append(name)
153162
table = agged.unstack(to_unstack)
154163

155164
if not dropna:

pandas/tests/reshape/test_pivot.py

+10
Original file line numberDiff line numberDiff line change
@@ -1513,6 +1513,16 @@ def test_crosstab_with_numpy_size(self):
15131513
columns=expected_column)
15141514
tm.assert_frame_equal(result, expected)
15151515

1516+
def test_crosstab_dup_index_names(self):
1517+
# GH 13279
1518+
s = pd.Series(range(3), name='foo')
1519+
result = pd.crosstab(s, s)
1520+
expected_index = pd.Index(range(3), name='foo')
1521+
expected = pd.DataFrame(np.eye(3, dtype=np.int64),
1522+
index=expected_index,
1523+
columns=expected_index)
1524+
tm.assert_frame_equal(result, expected)
1525+
15161526

15171527
class TestPivotAnnual(object):
15181528
"""

0 commit comments

Comments
 (0)