diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1dc635bebe731..bf63a51204f5c 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -221,6 +221,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`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 4c73e5d594d2b..51556fda6da04 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -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) @@ -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)) @@ -101,6 +103,7 @@ def pivot_table( dropna, margins_name, observed, + sort, ) return table.__finalize__(data, method="pivot_table") @@ -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``. @@ -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")