BUG: index label messed up when reset_level then unstack then sort_index · Issue #37510 · pandas-dev/pandas (original) (raw)
- I have checked that this issue has not already been reported.
- I have confirmed this bug exists on the latest version of pandas.
- (optional) I have confirmed this bug exists on the master branch of pandas.
Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.
Code Sample, a copy-pastable example
Your code here
import pandas as pd
df1 = pd.DataFrame({'id1': [1, 2, 3, 4], 'id2': [3,4,1,2], 'id3': [1,1,1,1], 'x': [1,2,3,4]}) df1.set_index(['id1', 'id2', 'id3'], inplace=True)
new_levels = ['n1', 'n2', 'n3', None] df1.index.set_levels(levels=new_levels, level='id1', inplace=True) df1.index.set_levels(levels=new_levels, level='id2', inplace=True)
df1.unstack('id3')[('x',1)].sort_index()
Problem description
I would expect the index after the reset_level operations should be just normal index, but when doing sort_index, it seems index level ‘id1’ of row 1 is incorrectly changed to ‘n1’ from NaN and the same for level ‘id2’ of row 2.
The result is:
id1 id2
n1 n2 4
n3 1
n2 n1 2
n3 n1 3
Name: (x, 1), dtype: int64
Expected Output
id1 id2
n1 n3 1
n2 NaN 2
n3 n1 3
NaN n2 4
Name: (x, 1), dtype: int64
Output of pd.show_versions()
INSTALLED VERSIONS
commit : f2ca0a2
python : 3.8.5.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.18362
machine : AMD64
processor : Intel64 Family 6 Model 94 Stepping 3, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252
pandas : 1.1.1
numpy : 1.19.0
pytz : 2020.1
dateutil : 2.8.1
pip : 20.2.3
setuptools : 47.1.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.5.1
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.18.1
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.2.2
numexpr : None
odfpy : None
openpyxl : 3.0.3
pandas_gbq : None
pyarrow : None
pytables : None
pyxlsb : None
s3fs : None
scipy : 1.5.0
sqlalchemy : 1.3.18
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None