Skip to content

BUG: unstack with sort=False scrambles data #58991

Closed
@mishavanbeek

Description

@mishavanbeek

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

assert pd.__version__ == "2.2.2"

df = pd.DataFrame(
    {
        "index1": [2, 1],
        "index2": [2, 1],
        "index3": [2, 1],
        "value": [2, 1],
    },
)
df = df.set_index(["index1", "index2", "index3"])


df.unstack(("index2", "index1"), sort=False)

Issue Description

When using triple indices and unstacking two, the data is mapped to the wrong index value when using sort=False. In the example the data should be on the diagonal.

Expected Behavior

The output with sort=True seems valid, but with the unsorted index.

Installed Versions

INSTALLED VERSIONS

commit : d9cdd2e
python : 3.11.6.final.0
python-bits : 64
OS : Darwin
OS-release : 23.4.0
Version : Darwin Kernel Version 23.4.0: Wed Feb 21 21:44:54 PST 2024; root:xnu-10063.101.15~2/RELEASE_ARM64_T6031
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8

pandas : 2.2.2
numpy : 1.26.4
pytz : 2024.1
dateutil : 2.9.0.post0
setuptools : 70.0.0
pip : 24.0
Cython : None
pytest : 8.2.2
hypothesis : None
...
zstandard : None
tzdata : 2024.1
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugDuplicate ReportDuplicate issue or pull requestReshapingConcat, Merge/Join, Stack/Unstack, Explode

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions