pandas-dev / pandas

Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
https://pandas.pydata.org
BSD 3-Clause "New" or "Revised" License
43.24k stars 17.79k forks source link

BUG: Undocumented behaviour of MultiIndex.rename #33778

Open simonjayhawkins opened 4 years ago

simonjayhawkins commented 4 years ago

Code Sample, a copy-pastable example

>>> import numpy as np
>>> import pandas as pd
>>>
>>> pd.__version__
'1.1.0.dev0+1349.g930a7f837'
>>>
>>> df = pd.DataFrame(
...     [[1, 2]],
...     columns=pd.MultiIndex.from_product([["a", "b"], ["c"]], names=["level0", "level1"]),
... )
>>> df
level0  a  b
level1  c  c
0       1  2
>>>
>>>
>>> df.columns.rename(["foo", "bar"], False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\simon\pandas\pandas\core\indexes\base.py", line 1248, in set_names
    raise TypeError("Names must be a string when a single level is provided.")
TypeError: Names must be a string when a single level is provided.
>>>

Problem description

from docs

Index.rename(self, name, inplace=False)

Undocumented behaviour arising from

https://github.com/pandas-dev/pandas/blob/73fd8a797dc45ab1ced1c1712e04852d8d4a7d09/pandas/core/indexes/multi.py#L247

This allows passing a level to rename since MultiIndex.rename is an alias for MutliIndex.set_names

https://pandas.pydata.org/docs/dev/reference/api/pandas.Index.set_names.html

there is no documentation for MultiIndex.rename, the documentation for Index.rename includes examples for MutliIndex

so the second argument is interpreted as level, but from the docs should be inplace

https://pandas.pydata.org/docs/dev/reference/api/pandas.Index.rename.html

Expected Output

MultiIndex([('a', 'c'),
            ('b', 'c')],
           names=['foo', 'bar'])
>>>

Output of pd.show_versions()

[paste the output of ``pd.show_versions()`` here leaving a blank line after the details tag]
nurakmal920207 commented 2 years ago

I am able to reproduce this bug, so I believe this bug has not been solved. Can you share more thoughts on this? Do you think only the documentation need to be updated, or should the code updated as well to remove the bug altogether?

jreback commented 2 years ago

@nurakmal920207 hence the open label on the issue

anyone in the community can submit a PR