Skip to content

DataFrame rename fails with TypeError when give a ChainMap instead of a dict #23859

Closed
@dave-kirby

Description

@dave-kirby

Example code:

>>> from collections import ChainMap
>>> import pandas as pd
>>> df = pd.DataFrame({'A': range(1, 11), 'B': np.random.randn(10)})
>>> df.rename(ChainMap({'A': 'a'}, {'B':'b'}), axis='columns')
...
TypeError: 'ChainMap' object is not callable

# also fails if called with the columns parameter:
>>> df.rename(columns=ChainMap({'A': 'a'}, {'B':'b'}))

I am trying to rename columns in a DataFrame using mappings from two or more dicts combined using the collections.ChainMap class, but it fails with a TypeError.

The docs for DataFrame.rename says

mapper, index, columns : dict-like or function, optional
dict-like or functions transformations to apply to
that axis' values. Use either mapper and axis to
specify the axis to target with mapper, or index and
columns

the ChainMap class should definitely qualify as "dict-like" since it implements the Mapping protocol:

>>> from collections import Mapping
>>> issubclass(ChainMap, Mapping)
True

I am using Python 3.6.6 with Pandas 0.23.4.

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