Search code examples
pythonpandasnaming

Renaming column and index values one expression


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'])


Solution

  • 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.