Skip to content

Commit 4ebca9d

Browse files
committed
ENH: do not sort resulting columns when sort=False
1 parent d49a244 commit 4ebca9d

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,7 @@ Reshaping
744744
- Bug in concanenation with ``IntegerDtype``, or ``FloatingDtype`` arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (:issue:`46379`)
745745
- Bug in :func:`concat` with identical key leads to error when indexing :class:`MultiIndex` (:issue:`46519`)
746746
- Bug in :meth:`DataFrame.join` with a list when using suffixes to join DataFrames with duplicate column names (:issue:`46396`)
747+
- Bug in :meth:`DataFrame.pivot_table` with ``sort=False`` results in sorted index (:issue:`17041`)
747748
-
748749

749750
Sparse

pandas/core/reshape/pivot.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ def __internal_pivot_table(
216216
)
217217
table = table.reindex(m, axis=1)
218218

219-
if isinstance(table, ABCDataFrame):
219+
if sort is True and isinstance(table, ABCDataFrame):
220220
table = table.sort_index(axis=1)
221221

222222
if fill_value is not None:

pandas/tests/reshape/test_pivot.py

+22
Original file line numberDiff line numberDiff line change
@@ -2167,6 +2167,28 @@ def test_pivot_table_sort_false(self):
21672167
)
21682168
tm.assert_frame_equal(result, expected)
21692169

2170+
def test_pivot_table_sort_false_with_multiple_values(self):
2171+
df = DataFrame(
2172+
{
2173+
"firstname": ["John", "Michael"],
2174+
"lastname": ["Foo", "Bar"],
2175+
"height": [173, 182],
2176+
"age": [47, 33],
2177+
}
2178+
)
2179+
result = df.pivot_table(
2180+
index=["lastname", "firstname"], values=["height", "age"], sort=False
2181+
)
2182+
expected = DataFrame(
2183+
[[173, 47], [182, 33]],
2184+
columns=["height", "age"],
2185+
index=MultiIndex.from_tuples(
2186+
[("Foo", "John"), ("Bar", "Michael")],
2187+
names=["lastname", "firstname"],
2188+
),
2189+
)
2190+
tm.assert_frame_equal(result, expected)
2191+
21702192
def test_pivot_table_with_margins_and_numeric_columns(self):
21712193
# GH 26568
21722194
df = DataFrame([["a", "x", 1], ["a", "y", 2], ["b", "y", 3], ["b", "z", 4]])

0 commit comments

Comments
 (0)