Skip to content

BUG: sort argument in unstack gives wrong results #55516

Closed
@sdementen

Description

@sdementen

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
from io import StringIO
sr = pandas.read_csv(StringIO(',z,a\nt,1.0,\nr,,5.0\ns,2.0,\nz,,2.0\nv,,4.0\nr,3.0,\n'),index_col=0).stack()
print(sr)
print(sr.unstack())
print(sr.unstack(sort=False))

Issue Description

the original series is

t  z    1.0
r  a    5.0
s  z    2.0
z  a    2.0
v  a    4.0
r  z    3.0
dtype: float64

the default unstack() call returns a dataframe sorted on the index

     z    a
r  3.0  5.0
s  2.0  NaN
t  1.0  NaN
v  NaN  4.0
z  NaN  2.0

while using the sort argument unstack(sort=False) gives wrong results yet a the dataframe index keeps the original order

     z    a
t  1.0  5.0
r  2.0  NaN
s  2.0  NaN
z  NaN  4.0
v  NaN  3.0

Expected Behavior

I would expect to get the dataframe with the index in the its original order but with the proper results

     z    a
t  1.0  NaN
r  3.0  5.0
s  2.0  NaN
z  NaN  2.0
v  NaN  4.0

(I can get this result with sr.unstack().reindex(sr.index.get_level_values(0).unique()))

Installed Versions

INSTALLED VERSIONS

commit : e86ed37
python : 3.11.6.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19045
machine : AMD64
processor : AMD64 Family 23 Model 96 Stepping 1, AuthenticAMD
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_Belgium.1252
pandas : 2.1.1
numpy : 1.26.0
pytz : 2023.3.post1
dateutil : 2.8.2
setuptools : 60.2.0
pip : 23.2.1
Cython : 0.29.36
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.16.1
pandas_datareader : None
bs4 : 4.12.2
bottleneck : None
dataframe-api-compat: None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.8.0
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.2
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : 2.0.21
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReshapingConcat, 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