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 13, 2022
1 parent d49a244 commit 4ebca9d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,7 @@ Reshaping
- Bug in concanenation with ``IntegerDtype``, or ``FloatingDtype`` arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (:issue:`46379`)
- Bug in :func:`concat` with identical key leads to error when indexing :class:`MultiIndex` (:issue:`46519`)
- Bug in :meth:`DataFrame.join` with a list when using suffixes to join DataFrames with duplicate column names (:issue:`46396`)
- Bug in :meth:`DataFrame.pivot_table` with ``sort=False`` results in sorted index (:issue:`17041`)
-

Sparse
Expand Down
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 4ebca9d

Please sign in to comment.