Skip to content

Commit

Permalink
ENH: do not sort resulting columns when sort=False
Browse files Browse the repository at this point in the history
  • Loading branch information
ShawnZhong committed May 11, 2022
1 parent d49a244 commit d351af4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def __internal_pivot_table(
)
table = table.reindex(m, axis=1)

if isinstance(table, ABCDataFrame):
if sort is True and isinstance(table, ABCDataFrame):
table = table.sort_index(axis=1)

if fill_value is not None:
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2167,6 +2167,28 @@ def test_pivot_table_sort_false(self):
)
tm.assert_frame_equal(result, expected)

def test_pivot_table_sort_false_with_multiple_values(self):
df = DataFrame(
{
"firstname": ["John", "Michael"],
"lastname": ["Foo", "Bar"],
"height": [173, 182],
"age": [47, 33],
}
)
result = df.pivot_table(
index=["lastname", "firstname"], values=["height", "age"], sort=False
)
expected = DataFrame(
[[173, 47], [182, 33]],
columns=["height", "age"],
index=MultiIndex.from_tuples(
[("Foo", "John"), ("Bar", "Michael")],
names=["lastname", "firstname"],
),
)
tm.assert_frame_equal(result, expected)

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

0 comments on commit d351af4

Please sign in to comment.