Skip to content

Commit efe962e

Browse files
committed
correct wrong if statement in crosstab and add tests for #35144
1 parent 15884f3 commit efe962e

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pandas/core/reshape/pivot.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -673,7 +673,7 @@ def _normalize(table, normalize, margins: bool, margins_name="All"):
673673

674674
# check if margin name is in (for MI cases) or equal to last
675675
# index/column and save the column and index margin
676-
if (margins_name not in table.iloc[-1, :].name) | (
676+
if (margins_name not in table.iloc[-1, :].name) & (
677677
margins_name != table.iloc[:, -1].name
678678
):
679679
raise ValueError(f"{margins_name} not in pivoted DataFrame")

pandas/tests/reshape/test_crosstab.py

+23
Original file line numberDiff line numberDiff line change
@@ -698,3 +698,26 @@ def test_margin_normalize(self):
698698
names=["A", "B"],
699699
)
700700
tm.assert_frame_equal(result, expected)
701+
702+
def test_crosstab_multiple_columns_normalize(self):
703+
df = DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
704+
"bar", "bar", "bar", "bar"],
705+
"B": ["one", "one", "one", "two", "two",
706+
"one", "one", "two", "two"],
707+
"C": ["small", "large", "large", "small",
708+
"small", "large", "small", "small",
709+
"large"],
710+
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
711+
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
712+
result = crosstab(index=df.C,
713+
columns=[df.A, df.B],
714+
margins=True,
715+
margins_name='margin', normalize=True)
716+
expected = DataFrame([[0.111111, 0.111111, 0.222222, 0.000000, 0.444444],
717+
[0.111111, 0.111111, 0.111111, 0.222222, 0.555556],
718+
[0.222222, 0.222222, 0.333333, 0.222222, 1.]],
719+
index=['large', 'small', 'margin'])
720+
expected.columns = MultiIndex( levels=[['bar', 'foo', 'margin'], ['', 'one', 'two']], codes=[[0, 0, 1, 1, 2], [1, 2, 1, 2, 0]], names=["A", "B"], )
721+
expected.index.name = 'C'
722+
tm.assert_frame_equal(result, expected)
723+

0 commit comments

Comments
 (0)