Skip to content

Commit 618f697

Browse files
quangngdphofl
authored andcommitted
BUG: pivot_table with margins and numeric columns (pandas-dev#55933)
* fix and add test * add whatsnew * rm comment
1 parent 7c7b725 commit 618f697

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

doc/source/whatsnew/v2.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@ Reshaping
466466
- Bug in :func:`merge` returning columns in incorrect order when left and/or right is empty (:issue:`51929`)
467467
- Bug in :meth:`pandas.DataFrame.melt` where an exception was raised if ``var_name`` was not a string (:issue:`55948`)
468468
- Bug in :meth:`pandas.DataFrame.melt` where it would not preserve the datetime (:issue:`55254`)
469+
- Bug in :meth:`pandas.DataFrame.pivot_table` where the row margin is incorrect when the columns have numeric names (:issue:`26568`)
469470

470471
Sparse
471472
^^^^^^

pandas/core/reshape/pivot.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -421,9 +421,10 @@ def _all_key(key):
421421
row_margin = data[cols + values].groupby(cols, observed=observed).agg(aggfunc)
422422
row_margin = row_margin.stack(future_stack=True)
423423

424-
# slight hack
425-
new_order = [len(cols)] + list(range(len(cols)))
426-
row_margin.index = row_margin.index.reorder_levels(new_order)
424+
# GH#26568. Use names instead of indices in case of numeric names
425+
new_order_indices = [len(cols)] + list(range(len(cols)))
426+
new_order_names = [row_margin.index.names[i] for i in new_order_indices]
427+
row_margin.index = row_margin.index.reorder_levels(new_order_names)
427428
else:
428429
row_margin = data._constructor_sliced(np.nan, index=result.columns)
429430

pandas/tests/reshape/test_pivot.py

+15
Original file line numberDiff line numberDiff line change
@@ -2666,3 +2666,18 @@ def test_pivot_table_handles_explicit_datetime_types(self):
26662666
names=["a", "date"],
26672667
)
26682668
tm.assert_index_equal(pivot.index, expected)
2669+
2670+
def test_pivot_table_with_margins_and_numeric_column_names(self):
2671+
# GH#26568
2672+
df = DataFrame([["a", "x", 1], ["a", "y", 2], ["b", "y", 3], ["b", "z", 4]])
2673+
2674+
result = df.pivot_table(
2675+
index=0, columns=1, values=2, aggfunc="sum", fill_value=0, margins=True
2676+
)
2677+
2678+
expected = DataFrame(
2679+
[[1, 2, 0, 3], [0, 3, 4, 7], [1, 5, 4, 10]],
2680+
columns=Index(["x", "y", "z", "All"], name=1),
2681+
index=Index(["a", "b", "All"], name=0),
2682+
)
2683+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)