Skip to content

Commit 9f9ba46

Browse files
ShawnZhongyehoshuadimarsky
authored andcommitted
ENH: do not sort resulting columns when sort=False (pandas-dev#46994)
1 parent 7bc8aaf commit 9f9ba46

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
@@ -795,6 +795,7 @@ Reshaping
795795
- Bug in concanenation with ``IntegerDtype``, or ``FloatingDtype`` arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (:issue:`46379`)
796796
- Bug in :func:`concat` with identical key leads to error when indexing :class:`MultiIndex` (:issue:`46519`)
797797
- Bug in :meth:`DataFrame.join` with a list when using suffixes to join DataFrames with duplicate column names (:issue:`46396`)
798+
- Bug in :meth:`DataFrame.pivot_table` with ``sort=False`` results in sorted index (:issue:`17041`)
798799
-
799800

800801
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
@@ -2181,6 +2181,28 @@ def test_pivot_table_sort_false(self):
21812181
)
21822182
tm.assert_frame_equal(result, expected)
21832183

2184+
def test_pivot_table_sort_false_with_multiple_values(self):
2185+
df = DataFrame(
2186+
{
2187+
"firstname": ["John", "Michael"],
2188+
"lastname": ["Foo", "Bar"],
2189+
"height": [173, 182],
2190+
"age": [47, 33],
2191+
}
2192+
)
2193+
result = df.pivot_table(
2194+
index=["lastname", "firstname"], values=["height", "age"], sort=False
2195+
)
2196+
expected = DataFrame(
2197+
[[173, 47], [182, 33]],
2198+
columns=["height", "age"],
2199+
index=MultiIndex.from_tuples(
2200+
[("Foo", "John"), ("Bar", "Michael")],
2201+
names=["lastname", "firstname"],
2202+
),
2203+
)
2204+
tm.assert_frame_equal(result, expected)
2205+
21842206
def test_pivot_table_with_margins_and_numeric_columns(self):
21852207
# GH 26568
21862208
df = DataFrame([["a", "x", 1], ["a", "y", 2], ["b", "y", 3], ["b", "z", 4]])

0 commit comments

Comments
 (0)