Skip to content

BUG: Check for duplicate names columns and index in crosstab #26717

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

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,17 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
common_idx = _get_objs_combined_axis(index + columns, intersect=True,
sort=False)

if len(set(rownames)) != len(rownames):
raise ValueError("Duplicated index/row names not allowed")
if len(set(colnames)) != len(colnames):
raise ValueError("Duplicated column names not allowed")

repeated_names = set(rownames).intersection(set(colnames))
if repeated_names:
raise ValueError("Column and rows cannot share the same names. "
"Repeated names: {repeated_names}"
.format(repeated_names=", ".join(repeated_names)))

data = {}
data.update(zip(rownames, index))
data.update(zip(colnames, columns))
Expand Down
30 changes: 22 additions & 8 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1830,16 +1830,30 @@ def test_crosstab_with_numpy_size(self):
columns=expected_column)
tm.assert_frame_equal(result, expected)


def test_crosstab_dup_index_names(self):
# GH 13279
s = pd.Series(range(3), name='foo')
s1 = pd.Series(range(3), name='foo')
s2 = s1 + 1

msg = "Column and rows cannot share the same names. " \
"Repeated names: foo"
with pytest.raises(ValueError, match=msg):
pd.crosstab(s1, s2)
with pytest.raises(ValueError, match=msg):
pd.crosstab(s1, [s2, s2.rename("bar")])

msg = "Duplicated column names not allowed"
with pytest.raises(ValueError, match=msg):
pd.crosstab(s1.rename("bar"), [s2, s2])
with pytest.raises(ValueError, match=msg):
pd.crosstab(s1.rename("bar"), [s2.rename("one"), s2, s2])

msg = "Duplicated index/row names not allowed"
with pytest.raises(ValueError, match=msg):
pd.crosstab([s1, s1], s2.rename("bar"))
with pytest.raises(ValueError, match=msg):
pd.crosstab([s1, s1, s1.rename("one")], s2.rename("bar"))

result = pd.crosstab(s, s)
expected_index = pd.Index(range(3), name='foo')
expected = pd.DataFrame(np.eye(3, dtype=np.int64),
index=expected_index,
columns=expected_index)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("names", [['a', ('b', 'c')],
[('a', 'b'), 'c']])
Expand Down