Skip to content

Crosstab hack #1

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

Open
wants to merge 1 commit into
base: crosstable_norm
Choose a base branch
from
Open
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
12 changes: 9 additions & 3 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,10 @@ def _normalize(table, normalize, margins, margins_name='All'):
elif margins is True:

column_margin = table.loc[:, margins_name].drop(margins_name)
index_margin = table.loc[margins_name, :].drop(margins_name)
if isinstance(table.index, MultiIndex):
index_margin = table.loc[margins_name, :].iloc[0].drop(margins_name) # GH 17029 and possibly more
else:
index_margin = table.loc[margins_name, :].drop(margins_name)
table = table.drop(margins_name, axis=1).drop(margins_name)
# to keep index and columns names
table_index_names = table.index.names
Expand All @@ -582,8 +585,11 @@ def _normalize(table, normalize, margins, margins_name='All'):
column_margin = column_margin / column_margin.sum()
index_margin = index_margin / index_margin.sum()
index_margin.loc[margins_name] = 1
table = concat([table, column_margin], axis=1)
table = table.append(index_margin)
table[margins_name] = column_margin
if isinstance(table.index, MultiIndex):
table.loc[(margins_name, ''), :] = index_margin # GH 17024 ?
else:
table.loc[margins_name] = index_margin

table = table.fillna(0)

Expand Down