Skip to content

BUG: pivot_table with margins and numeric columns #55933

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 4 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ Reshaping
- Bug in :func:`merge_asof` raising ``TypeError`` when ``by`` dtype is not ``object``, ``int64``, or ``uint64`` (:issue:`22794`)
- Bug in :func:`merge` returning columns in incorrect order when left and/or right is empty (:issue:`51929`)
- Bug in :meth:`pandas.DataFrame.melt` where it would not preserve the datetime (:issue:`55254`)
-
- Bug in :meth:`pandas.DataFrame.pivot_table` where the row margin is incorrect when the columns have numeric names (:issue:`26568`)

Sparse
^^^^^^
Expand Down
7 changes: 4 additions & 3 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,9 +421,10 @@ def _all_key(key):
row_margin = data[cols + values].groupby(cols, observed=observed).agg(aggfunc)
row_margin = row_margin.stack(future_stack=True)

# slight hack
new_order = [len(cols)] + list(range(len(cols)))
row_margin.index = row_margin.index.reorder_levels(new_order)
# GH#26568. Use names instead of indices in case of numeric names
new_order_indices = [len(cols)] + list(range(len(cols)))
new_order_names = [row_margin.index.names[i] for i in new_order_indices]
row_margin.index = row_margin.index.reorder_levels(new_order_names)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are row_margin.index.names guaranteed to be unique?

Copy link
Contributor Author

@quangngd quangngd Nov 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case, row_margin.index.names are the names of the columns in the original df. They should be unique. If user try to pivot_table on a df with duplicated column names, upstream code would scream first.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the explanation. Could you resolve the merge conflict otherwise looks good.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolved

else:
row_margin = data._constructor_sliced(np.nan, index=result.columns)

Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2664,3 +2664,18 @@ def test_pivot_table_handles_explicit_datetime_types(self):
names=["a", "date"],
)
tm.assert_index_equal(pivot.index, expected)

def test_pivot_table_with_margins_and_numeric_column_names(self):
# GH#26568
df = DataFrame([["a", "x", 1], ["a", "y", 2], ["b", "y", 3], ["b", "z", 4]])

result = df.pivot_table(
index=0, columns=1, values=2, aggfunc="sum", fill_value=0, margins=True
)

expected = DataFrame(
[[1, 2, 0, 3], [0, 3, 4, 7], [1, 5, 4, 10]],
columns=Index(["x", "y", "z", "All"], name=1),
index=Index(["a", "b", "All"], name=0),
)
tm.assert_frame_equal(result, expected)