Skip to content

Clarify that MultiIndex.set_levels() interprets passed values as new components of the .levels attribute #28294

Closed
@pepicello

Description

@pepicello

Code Sample, a copy-pastable example if possible

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(3, 3), columns=pd.MultiIndex.from_tuples([(1, 2), (1, 4), (5, 6)]))
df.columns = df.columns.set_levels([1, 1, 3], level=0)

Which raises a ValueError:

ValueError: Level values must be unique: [1, 1, 3] on level 0

Problem description

Despite a dataframe with non-unique MultiIndex can be created, they cannot be set using set_levels(). Is this behaviour expected? I believe non-unique level values were not allowed for a period of time (#18882), but then they were allowed again (#21423), so I am not sure which is the current convention.

Expected Output

          1                   3
          2         4         6
0  0.317669  0.329142  0.056725
1  0.969472  0.340309  0.135204
2  0.242408  0.934748  0.683186

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.7.4.final.0
python-bits : 64
OS : Windows
OS-release : 10
machine : AMD64
processor : Intel64 Family 6 Model 158 Stepping 10, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.None

pandas : 0.25.1
numpy : 1.16.4
pytz : 2019.2
dateutil : 2.8.0
pip : 19.2.2
setuptools : 41.0.1
Cython : 0.29.13
pytest : 5.1.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 1.1.8
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.10.1
IPython : 7.8.0
pandas_datareader: None
bs4 : None
bottleneck : 1.2.1
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.1.1
numexpr : None
odfpy : None
openpyxl : 2.6.2
pandas_gbq : None
pyarrow : None
pytables : None
s3fs : None
scipy : 1.3.1
sqlalchemy : 1.3.7
tables : None
xarray : None
xlrd : 1.2.0
xlwt : None
xlsxwriter : 1.1.8

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions