Skip to content

Index.map fails when index has a name and mapping returns tuple #20990

Closed
@willvousden

Description

@willvousden

This is related to #18696.

Code Sample

import pandas as pd
import numpy as np

count = 6
index = pd.date_range('2018-01-01', periods=count, freq='M')

a = pd.Series(np.arange(count), index=index)
a.index.name = 'name' # This causes the failure.

b = a.copy()
b.index = a.index.map(lambda x: (x.year, x.month))
print(b)

Problem description

The above code fails with ValueError: Names should be list-like for a MultiIndex.

I understand that a scalar name can't meaningfully be carried over to a MultiIndex, but there's no documentation stating that Index.map will fail under these conditions, and moreover there's no way to use Index.map here without either

  1. modifying the source index in-place to remove its name, which is destructive, or
  2. creating a temporary copy in order to set name to None, which is wasteful.

I think a better solution would be to discard the name when returning a MultiIndex if the existing name isn't compatible, and then to make this behaviour clear in the documentation.

Expected Output

2018  1    0
      2    1
      3    2
      4    3
      5    4
      6    5
dtype: int64

Output of pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.5.2.final.0
python-bits: 64
OS: Linux
OS-release: 4.4.0-119-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.22.0
pytest: None
pip: 10.0.1
setuptools: 39.1.0
Cython: None
numpy: 1.14.3
scipy: None
pyarrow: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.7.2
pytz: 2018.4
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions