Skip to content

ENH: Add sort keyword to stack #53282

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 6 commits into from
May 30, 2023
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/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ Other enhancements
- Let :meth:`DataFrame.to_feather` accept a non-default :class:`Index` and non-string column names (:issue:`51787`)
- Performance improvement in :func:`read_csv` (:issue:`52632`) with ``engine="c"``
- :meth:`Categorical.from_codes` has gotten a ``validate`` parameter (:issue:`50975`)
- :meth:`DataFrame.stack` gained the ``sort`` keyword to dictate whether the resulting :class:`MultiIndex` levels are sorted (:issue:`15105`)
- Added ``engine_kwargs`` parameter to :meth:`DataFrame.to_excel` (:issue:`53220`)
- Performance improvement in :func:`concat` with homogeneous ``np.float64`` or ``np.float32`` dtypes (:issue:`52685`)
- Performance improvement in :meth:`DataFrame.filter` when ``items`` is given (:issue:`52941`)
Expand Down
8 changes: 5 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -8994,7 +8994,7 @@ def pivot_table(
sort=sort,
)

def stack(self, level: Level = -1, dropna: bool = True):
def stack(self, level: Level = -1, dropna: bool = True, sort: bool = True):
"""
Stack the prescribed level(s) from columns to index.

Expand All @@ -9020,6 +9020,8 @@ def stack(self, level: Level = -1, dropna: bool = True):
axis can create combinations of index and column values
that are missing from the original dataframe. See Examples
section.
sort : bool, default True
Whether to sort the levels of the resulting MultiIndex.

Returns
-------
Expand Down Expand Up @@ -9163,9 +9165,9 @@ def stack(self, level: Level = -1, dropna: bool = True):
)

if isinstance(level, (tuple, list)):
result = stack_multiple(self, level, dropna=dropna)
result = stack_multiple(self, level, dropna=dropna, sort=sort)
else:
result = stack(self, level, dropna=dropna)
result = stack(self, level, dropna=dropna, sort=sort)

return result.__finalize__(self, method="stack")

Expand Down
21 changes: 13 additions & 8 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from pandas.core.dtypes.missing import notna

import pandas.core.algorithms as algos
from pandas.core.algorithms import unique
from pandas.core.arrays.categorical import factorize_from_iterable
from pandas.core.construction import ensure_wrapped_if_datetimelike
from pandas.core.frame import DataFrame
Expand Down Expand Up @@ -545,7 +546,7 @@ def _unstack_extension_series(series: Series, level, fill_value) -> DataFrame:
return result


def stack(frame: DataFrame, level=-1, dropna: bool = True):
def stack(frame: DataFrame, level=-1, dropna: bool = True, sort: bool = True):
"""
Convert DataFrame to Series with multi-level Index. Columns become the
second level of the resulting hierarchical index
Expand All @@ -567,7 +568,9 @@ def factorize(index):
level_num = frame.columns._get_level_number(level)

if isinstance(frame.columns, MultiIndex):
return _stack_multi_columns(frame, level_num=level_num, dropna=dropna)
return _stack_multi_columns(
frame, level_num=level_num, dropna=dropna, sort=sort
)
elif isinstance(frame.index, MultiIndex):
new_levels = list(frame.index.levels)
new_codes = [lab.repeat(K) for lab in frame.index.codes]
Expand Down Expand Up @@ -620,13 +623,13 @@ def factorize(index):
return frame._constructor_sliced(new_values, index=new_index)


def stack_multiple(frame: DataFrame, level, dropna: bool = True):
def stack_multiple(frame: DataFrame, level, dropna: bool = True, sort: bool = True):
# If all passed levels match up to column names, no
# ambiguity about what to do
if all(lev in frame.columns.names for lev in level):
result = frame
for lev in level:
result = stack(result, lev, dropna=dropna)
result = stack(result, lev, dropna=dropna, sort=sort)

# Otherwise, level numbers may change as each successive level is stacked
elif all(isinstance(lev, int) for lev in level):
Expand All @@ -639,7 +642,7 @@ def stack_multiple(frame: DataFrame, level, dropna: bool = True):

while level:
lev = level.pop(0)
result = stack(result, lev, dropna=dropna)
result = stack(result, lev, dropna=dropna, sort=sort)
# Decrement all level numbers greater than current, as these
# have now shifted down by one
level = [v if v <= lev else v - 1 for v in level]
Expand Down Expand Up @@ -681,7 +684,7 @@ def _stack_multi_column_index(columns: MultiIndex) -> MultiIndex:


def _stack_multi_columns(
frame: DataFrame, level_num: int = -1, dropna: bool = True
frame: DataFrame, level_num: int = -1, dropna: bool = True, sort: bool = True
) -> DataFrame:
def _convert_level_number(level_num: int, columns: Index):
"""
Expand Down Expand Up @@ -711,7 +714,7 @@ def _convert_level_number(level_num: int, columns: Index):
roll_columns = roll_columns.swaplevel(lev1, lev2)
this.columns = mi_cols = roll_columns

if not mi_cols._is_lexsorted():
if not mi_cols._is_lexsorted() and sort:
Copy link
Member

@rhshadrach rhshadrach Jun 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if this is behaving as intended. In the example below, I would think that the rows would be swapped (the stacked 2nd level of the index being 0 1 instead of 1 0)

levels = ((0, 1), (1, 0))
stack_lev = 1
columns = MultiIndex(levels=levels, codes=[[0, 0, 1, 1], [0, 1, 0, 1]])
df = DataFrame(columns=columns, data=[range(4)])
df_stacked = df.stack(stack_lev, sort=True)
print(df_stacked)
#      0  1
# 0 1  0  2
#   0  1  3

# Expected?
#      0  1
# 0 0  1  3
#   1  0  2

mi_cols._is_lexsorted() is checking if the codes are lexsorted (they are [[0, 0, 1, 1], [0, 1, 0, 1]] here) but not if the values are sorted (they are [[0, 1], [1, 0]] here).

Should sort be sorting the level values?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice find. Yeah I agree and I think the level values should be sorted here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I plan on putting up a PR for this.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

# Workaround the edge case where 0 is one of the column names,
# which interferes with trying to sort based on the first
# level
Expand All @@ -725,7 +728,9 @@ def _convert_level_number(level_num: int, columns: Index):
# time to ravel the values
new_data = {}
level_vals = mi_cols.levels[-1]
level_codes = sorted(set(mi_cols.codes[-1]))
level_codes = unique(mi_cols.codes[-1])
if sort:
level_codes = np.sort(level_codes)
level_vals_nan = level_vals.insert(len(level_vals), None)

level_vals_used = np.take(level_vals_nan, level_codes)
Expand Down
42 changes: 42 additions & 0 deletions pandas/tests/frame/test_stack_unstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -1357,6 +1357,48 @@ def test_unstack_non_slice_like_blocks(using_array_manager):
tm.assert_frame_equal(res, expected)


def test_stack_sort_false():
# GH 15105
data = [[1, 2, 3.0, 4.0], [2, 3, 4.0, 5.0], [3, 4, np.nan, np.nan]]
df = DataFrame(
data,
columns=MultiIndex(
levels=[["B", "A"], ["x", "y"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
),
)
result = df.stack(level=0, sort=False)
expected = DataFrame(
{"x": [1.0, 3.0, 2.0, 4.0, 3.0], "y": [2.0, 4.0, 3.0, 5.0, 4.0]},
index=MultiIndex.from_arrays([[0, 0, 1, 1, 2], ["B", "A", "B", "A", "B"]]),
)
tm.assert_frame_equal(result, expected)

# Codes sorted in this call
df = DataFrame(
data,
columns=MultiIndex.from_arrays([["B", "B", "A", "A"], ["x", "y", "x", "y"]]),
)
result = df.stack(level=0, sort=False)
tm.assert_frame_equal(result, expected)


def test_stack_sort_false_multi_level():
# GH 15105
idx = MultiIndex.from_tuples([("weight", "kg"), ("height", "m")])
df = DataFrame([[1.0, 2.0], [3.0, 4.0]], index=["cat", "dog"], columns=idx)
result = df.stack([0, 1], sort=False)
expected_index = MultiIndex.from_tuples(
[
("cat", "weight", "kg"),
("cat", "height", "m"),
("dog", "weight", "kg"),
("dog", "height", "m"),
]
)
expected = Series([1.0, 2.0, 3.0, 4.0], index=expected_index)
tm.assert_series_equal(result, expected)


class TestStackUnstackMultiLevel:
def test_unstack(self, multiindex_year_month_day_dataframe_random_data):
# just check that it works for now
Expand Down