Skip to content

BUG: pd.crosstab(s1, s2) handle column index incorrectly when both series have tuple names #30978

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 11 commits into from
Jan 17, 2020
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ Reshaping
^^^^^^^^^

-
-
- Bug in :func:`crosstab` when inputs are two Series and have tuple names, the output will keep dummy MultiIndex as columns. (:issue:`18321`)

Sparse
^^^^^^
Expand Down
9 changes: 8 additions & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,8 @@ def crosstab(
from pandas import DataFrame

df = DataFrame(data, index=common_idx)
original_df_cols = df.columns

if values is None:
df["__dummy__"] = 0
kwargs = {"aggfunc": len, "fill_value": 0}
Expand All @@ -587,7 +589,7 @@ def crosstab(
kwargs = {"aggfunc": aggfunc}

table = df.pivot_table(
"__dummy__",
["__dummy__"],
index=rownames,
columns=colnames,
margins=margins,
Expand All @@ -596,6 +598,11 @@ def crosstab(
**kwargs,
)

# Remove extra level from `[__dummy__]` pivoting
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 give a comment on why you are doing this.

if not table.empty:
cols_diff = df.columns.difference(original_df_cols)[0]
table = table[cols_diff]

# Post-process
if normalize is not False:
table = _normalize(
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2549,6 +2549,19 @@ def test_crosstab_tuple_name(self, names):
result = pd.crosstab(s1, s2)
tm.assert_frame_equal(result, expected)

def test_crosstab_both_tuple_names(self):
# GH 18321
s1 = pd.Series(range(3), name=("a", "b"))
s2 = pd.Series(range(3), name=("c", "d"))

expected = pd.DataFrame(
np.eye(3, dtype="int64"),
index=pd.Index(range(3), name=("a", "b")),
columns=pd.Index(range(3), name=("c", "d")),
)
result = crosstab(s1, s2)
tm.assert_frame_equal(result, expected)

def test_crosstab_unsorted_order(self):
df = pd.DataFrame({"b": [3, 1, 2], "a": [5, 4, 6]}, index=["C", "A", "B"])
result = pd.crosstab(df.index, [df.b, df.a])
Expand Down