Skip to content

DataFrame.replace with inplace=True fails when column names are not unique #9106

Open
@djrobust

Description

@djrobust
  • replace should not itself do anything internally w.r.t. chained indexing (should be slightly refactored)
  • might need a test to show the SettingWithCopyWarning on this example
data = pd.DataFrame({0: ['a', 'b', 'c'], 1: ['1', '2', '3']})
data.columns = [0, 0]
data.index=['<3', 'u', 'i']
index_order = ['i', '<3', 'u']
index_dict = dict([(index, order) for order, index in enumerate(index_order)])

data['index_rank'] = list(data.index)

data['index_rank'].replace(index_dict, inplace=True)
print(data)
    0  0  index_rank
<3  a  1         <3
u   b  2          u
i   c  3          i
data['index_rank'] = data['index_rank'].replace(index_dict, inplace=False)
print(data)
    0  0  index_rank
<3  a  1           1
u   b  2           2
i   c  3           0

Assuring unique column names yields the expected behavior.

data = pd.DataFrame.from_items([(0, ['a', 'b', 'c']), (1, ['1', '2', '3'])])
data.index=['<3', 'u', 'i']
index_order = ['i', '<3', 'u']
index_dict = dict([(index, order) for order, index in enumerate(index_order)])

data['index_rank'] = list(data.index)

data['index_rank'].replace(index_dict, inplace=True)
print(data)
    0  1  index_rank
<3  a  1           1
u   b  2           2
i   c  3           0

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocsinplaceRelating to inplace parameter or equivalentreplacereplace method

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions