Skip to content

Commit

Permalink
Add keyword sort to pivot_table (pandas-dev#40954)
Browse files Browse the repository at this point in the history
  • Loading branch information
phofl authored and yeshsurya committed Apr 21, 2021
1 parent 57c912b commit 118afad
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
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 @@ -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`)
-

.. ---------------------------------------------------------------------------
Expand Down
7 changes: 7 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -7781,6 +7781,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 @@ -7884,6 +7889,7 @@ def pivot_table(
dropna=True,
margins_name="All",
observed=False,
sort=True,
) -> DataFrame:
from pandas.core.reshape.pivot import pivot_table

Expand All @@ -7898,6 +7904,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

0 comments on commit 118afad

Please sign in to comment.