Skip to content

Commit 855696c

Browse files
authored
Add keyword sort to pivot_table (#40954)
1 parent eaaefd1 commit 855696c

File tree

4 files changed

+35
-1
lines changed

4 files changed

+35
-1
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ Other enhancements
221221
- :meth:`pandas.read_csv` and :meth:`pandas.read_json` expose the argument ``encoding_errors`` to control how encoding errors are handled (:issue:`39450`)
222222
- :meth:`.GroupBy.any` and :meth:`.GroupBy.all` use Kleene logic with nullable data types (:issue:`37506`)
223223
- :meth:`.GroupBy.any` and :meth:`.GroupBy.all` return a ``BooleanDtype`` for columns with nullable data types (:issue:`33449`)
224+
- Add keyword ``sort`` to :func:`pivot_table` to allow non-sorting of the result (:issue:`39143`)
224225
-
225226

226227
.. ---------------------------------------------------------------------------

pandas/core/frame.py

+7
Original file line numberDiff line numberDiff line change
@@ -7781,6 +7781,11 @@ def pivot(self, index=None, columns=None, values=None) -> DataFrame:
77817781
77827782
.. versionchanged:: 0.25.0
77837783
7784+
sort : bool, default True
7785+
Specifies if the result should be sorted.
7786+
7787+
.. versionadded:: 1.3.0
7788+
77847789
Returns
77857790
-------
77867791
DataFrame
@@ -7884,6 +7889,7 @@ def pivot_table(
78847889
dropna=True,
78857890
margins_name="All",
78867891
observed=False,
7892+
sort=True,
78877893
) -> DataFrame:
78887894
from pandas.core.reshape.pivot import pivot_table
78897895

@@ -7898,6 +7904,7 @@ def pivot_table(
78987904
dropna=dropna,
78997905
margins_name=margins_name,
79007906
observed=observed,
7907+
sort=sort,
79017908
)
79027909

79037910
def stack(self, level: Level = -1, dropna: bool = True):

pandas/core/reshape/pivot.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ def pivot_table(
6464
dropna=True,
6565
margins_name="All",
6666
observed=False,
67+
sort=True,
6768
) -> DataFrame:
6869
index = _convert_by(index)
6970
columns = _convert_by(columns)
@@ -83,6 +84,7 @@ def pivot_table(
8384
dropna=dropna,
8485
margins_name=margins_name,
8586
observed=observed,
87+
sort=sort,
8688
)
8789
pieces.append(_table)
8890
keys.append(getattr(func, "__name__", func))
@@ -101,6 +103,7 @@ def pivot_table(
101103
dropna,
102104
margins_name,
103105
observed,
106+
sort,
104107
)
105108
return table.__finalize__(data, method="pivot_table")
106109

@@ -116,6 +119,7 @@ def __internal_pivot_table(
116119
dropna: bool,
117120
margins_name: str,
118121
observed: bool,
122+
sort: bool,
119123
) -> DataFrame:
120124
"""
121125
Helper of :func:`pandas.pivot_table` for any non-list ``aggfunc``.
@@ -157,7 +161,7 @@ def __internal_pivot_table(
157161
pass
158162
values = list(values)
159163

160-
grouped = data.groupby(keys, observed=observed)
164+
grouped = data.groupby(keys, observed=observed, sort=sort)
161165
agged = grouped.agg(aggfunc)
162166
if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns):
163167
agged = agged.dropna(how="all")

pandas/tests/reshape/test_pivot.py

+22
Original file line numberDiff line numberDiff line change
@@ -2115,6 +2115,28 @@ def test_pivot_table_doctest_case(self):
21152115
expected = DataFrame(vals, columns=cols, index=index)
21162116
tm.assert_frame_equal(table, expected)
21172117

2118+
def test_pivot_table_sort_false(self):
2119+
# GH#39143
2120+
df = DataFrame(
2121+
{
2122+
"a": ["d1", "d4", "d3"],
2123+
"col": ["a", "b", "c"],
2124+
"num": [23, 21, 34],
2125+
"year": ["2018", "2018", "2019"],
2126+
}
2127+
)
2128+
result = df.pivot_table(
2129+
index=["a", "col"], columns="year", values="num", aggfunc="sum", sort=False
2130+
)
2131+
expected = DataFrame(
2132+
[[23, np.nan], [21, np.nan], [np.nan, 34]],
2133+
columns=Index(["2018", "2019"], name="year"),
2134+
index=MultiIndex.from_arrays(
2135+
[["d1", "d4", "d3"], ["a", "b", "c"]], names=["a", "col"]
2136+
),
2137+
)
2138+
tm.assert_frame_equal(result, expected)
2139+
21182140

21192141
class TestPivot:
21202142
def test_pivot(self):

0 commit comments

Comments
 (0)