Skip to content
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

ENH: do not sort resulting columns when sort=False #46994

Merged
merged 2 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
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
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 @@ -745,6 +745,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