Skip to content

BUG: Exception with unstack(sort=False) and NA in index #61221

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
2 of 3 tasks
jlumpe opened this issue Apr 3, 2025 · 2 comments · May be fixed by #61226
Open
2 of 3 tasks

BUG: Exception with unstack(sort=False) and NA in index #61221

jlumpe opened this issue Apr 3, 2025 · 2 comments · May be fixed by #61226
Labels
Bug ExtensionArray Extending pandas with custom dtypes or arrays. Reshaping Concat, Merge/Join, Stack/Unstack, Explode

Comments

@jlumpe
Copy link

jlumpe commented Apr 3, 2025

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

levels1 = ['b', 'a']
levels2 = pd.Index([1, 2, 3, pd.NA], dtype=pd.Int64Dtype())
index = pd.MultiIndex.from_product([levels1, levels2], names=['level1', 'level2'])

df = pd.DataFrame(dict(value=range(len(index))), index=index)
print(df)

print(df.unstack(level='level2'))

print(df.unstack(level='level2', sort=False))
               value
level1 level2
b      1           0
       2           1
       3           2
       <NA>        3
a      1           4
       2           5
       3           6
       <NA>        7
       value
level2  <NA>  1  2  3
level1
a          3  0  1  2
b          7  4  5  6
Traceback (most recent call last):
  File "/home/jared/tmp/./250402-pd-test.py", line 15, in <module>
    print(df.unstack(level='level2', sort=False))
          ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jared/opt/mambaforge/envs/pd-test/lib/python3.13/site-packages/pandas/core/frame.py", line 9928, in unstack
    result = unstack(self, level, fill_value, sort)
  File "/home/jared/opt/mambaforge/envs/pd-test/lib/python3.13/site-packages/pandas/core/reshape/reshape.py", line 504, in unstack
    return _unstack_frame(obj, level, fill_value=fill_value, sort=sort)
  File "/home/jared/opt/mambaforge/envs/pd-test/lib/python3.13/site-packages/pandas/core/reshape/reshape.py", line 537, in _unstack_frame
    return unstacker.get_result(
           ~~~~~~~~~~~~~~~~~~~~^
        obj._values, value_columns=obj.columns, fill_value=fill_value
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/jared/opt/mambaforge/envs/pd-test/lib/python3.13/site-packages/pandas/core/reshape/reshape.py", line 242, in get_result
    return self.constructor(
           ~~~~~~~~~~~~~~~~^
        values, index=index, columns=columns, dtype=values.dtype
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/jared/opt/mambaforge/envs/pd-test/lib/python3.13/site-packages/pandas/core/frame.py", line 827, in __init__
    mgr = ndarray_to_mgr(
        data,
    ...<4 lines>...
        typ=manager,
    )
  File "/home/jared/opt/mambaforge/envs/pd-test/lib/python3.13/site-packages/pandas/core/internals/construction.py", line 336, in ndarray_to_mgr
    _check_values_indices_shape_match(values, index, columns)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jared/opt/mambaforge/envs/pd-test/lib/python3.13/site-packages/pandas/core/internals/construction.py", line 420, in _check_values_indices_shape_match
    raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
ValueError: Shape of passed values is (2, 4), indices imply (2, 5)

Issue Description

With a MultiIndex level of Int64Dtype() containing NA values, DataFrame.unstack() produces the expected result with sort=True (default) but causes an exception with sort=False. This does not occur if the NA value is removed from the index.

Expected Behavior

No exception, the returned DataFrame has level in the original order (['b', 'a']).

Installed Versions

INSTALLED VERSIONS

commit : 0691c5c
python : 3.13.2
python-bits : 64
OS : Linux
OS-release : 5.15.167.4-microsoft-standard-WSL2
Version : #1 SMP Tue Nov 5 00:21:55 UTC 2024
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : C.UTF-8
LOCALE : C.UTF-8

pandas : 2.2.3
numpy : 2.2.4
pytz : 2024.1
dateutil : 2.9.0.post0
pip : 25.0.1
Cython : None
sphinx : None
IPython : 9.0.2
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : None
lxml.etree : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : None
pyreadstat : None
pytest : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2025.2
qtpy : None
pyqt5 : None

@jlumpe jlumpe added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Apr 3, 2025
@gsmll
Copy link

gsmll commented Apr 3, 2025

take

gsmll pushed a commit to gsmll/pandas-gsmll that referenced this issue Apr 3, 2025
gsmll pushed a commit to gsmll/pandas-gsmll that referenced this issue Apr 3, 2025
@snitish
Copy link
Member

snitish commented Apr 4, 2025

Thanks for reporting. Confirmed on main. PRs to fix are welcome.

@snitish snitish added Reshaping Concat, Merge/Join, Stack/Unstack, Explode ExtensionArray Extending pandas with custom dtypes or arrays. and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Apr 4, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Bug ExtensionArray Extending pandas with custom dtypes or arrays. Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants