Skip to content

Add keyword sort to pivot_table #40954

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

Merged
merged 1 commit into from
Apr 20, 2021
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.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ Other enhancements
- :meth:`pandas.read_csv` and :meth:`pandas.read_json` expose the argument ``encoding_errors`` to control how encoding errors are handled (:issue:`39450`)
- :meth:`.GroupBy.any` and :meth:`.GroupBy.all` use Kleene logic with nullable data types (:issue:`37506`)
- :meth:`.GroupBy.any` and :meth:`.GroupBy.all` return a ``BooleanDtype`` for columns with nullable data types (:issue:`33449`)
- Add keyword ``sort`` to :func:`pivot_table` to allow non-sorting of the result (:issue:`39143`)
-

.. ---------------------------------------------------------------------------
Expand Down
7 changes: 7 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -7664,6 +7664,11 @@ def pivot(self, index=None, columns=None, values=None) -> DataFrame:

.. versionchanged:: 0.25.0

sort : bool, default True
Specifies if the result should be sorted.

.. versionadded:: 1.3.0

Returns
-------
DataFrame
Expand Down Expand Up @@ -7767,6 +7772,7 @@ def pivot_table(
dropna=True,
margins_name="All",
observed=False,
sort=True,
) -> DataFrame:
from pandas.core.reshape.pivot import pivot_table

Expand All @@ -7781,6 +7787,7 @@ def pivot_table(
dropna=dropna,
margins_name=margins_name,
observed=observed,
sort=sort,
)

def stack(self, level: Level = -1, dropna: bool = True):
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ def pivot_table(
dropna=True,
margins_name="All",
observed=False,
sort=True,
) -> DataFrame:
index = _convert_by(index)
columns = _convert_by(columns)
Expand All @@ -83,6 +84,7 @@ def pivot_table(
dropna=dropna,
margins_name=margins_name,
observed=observed,
sort=sort,
)
pieces.append(_table)
keys.append(getattr(func, "__name__", func))
Expand All @@ -101,6 +103,7 @@ def pivot_table(
dropna,
margins_name,
observed,
sort,
)
return table.__finalize__(data, method="pivot_table")

Expand All @@ -116,6 +119,7 @@ def __internal_pivot_table(
dropna: bool,
margins_name: str,
observed: bool,
sort: bool,
) -> DataFrame:
"""
Helper of :func:`pandas.pivot_table` for any non-list ``aggfunc``.
Expand Down Expand Up @@ -157,7 +161,7 @@ def __internal_pivot_table(
pass
values = list(values)

grouped = data.groupby(keys, observed=observed)
grouped = data.groupby(keys, observed=observed, sort=sort)
agged = grouped.agg(aggfunc)
if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns):
agged = agged.dropna(how="all")
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 @@ -2115,6 +2115,28 @@ def test_pivot_table_doctest_case(self):
expected = DataFrame(vals, columns=cols, index=index)
tm.assert_frame_equal(table, expected)

def test_pivot_table_sort_false(self):
# GH#39143
df = DataFrame(
{
"a": ["d1", "d4", "d3"],
"col": ["a", "b", "c"],
"num": [23, 21, 34],
"year": ["2018", "2018", "2019"],
}
)
result = df.pivot_table(
index=["a", "col"], columns="year", values="num", aggfunc="sum", sort=False
)
expected = DataFrame(
[[23, np.nan], [21, np.nan], [np.nan, 34]],
columns=Index(["2018", "2019"], name="year"),
index=MultiIndex.from_arrays(
[["d1", "d4", "d3"], ["a", "b", "c"]], names=["a", "col"]
),
)
tm.assert_frame_equal(result, expected)


class TestPivot:
def test_pivot(self):
Expand Down