Home > Mobile >  Renaming column and index values one expression
Renaming column and index values one expression

Time:01-30

I'm not sure why this code isn't working. If I define tankwater.columns = or tankwater.index = expressions separatly the columns and index are renamed, but when I try and combine them using the rename function I get "list object is not callable."

It's probably something simple.. Thanks in advance.

tankwater = tankwater.rename(index = ['Date 1', 'Date 2'], columns = ['Tank1','Tank 2', 'Tank 3', 'Total water'])

CodePudding user response:

You could use dicts instead of lists where the keys are the old values and the items the new ones. Like so:

tankwater = tankwater.rename(index = {'oldindex1':'Date 1',
                                      'oldindex2':'Date 2'},
                             columns = {'oldcolumn1': 'Tank1',
                                        'oldcolumn2': 'Tank 2',
                                        'oldcolumn3': 'Tank 3',
                                        'oldcolumn4': 'Total water'})

Added code for easier use for the example provided:

tankwater = tankwater.rename(index = dict(zip(tankwater.index, ['Date 1', 'Date 2'])),
                             columns = dict(zip(tankwater.columns, ['Tank1','Tank 2', 'Tank 3', 'Total water'])))

Where old indexes and old columns are the names to be replaced.

CodePudding user response:

You must use a dict containing the old column/index labels and the new ones, but you can use dict zip to do it dynamically:

tankwater = tankwater.rename(
    index=dict(zip(tankwater.index, ['Date 1', 'Date 2'])),
    columns=dict(zip(tankwater.columns, ['Tank1','Tank 2', 'Tank 3', 'Total water']))
)
  •  Tags:  
  • Related