Search code examples
pandasindexingrename

Mapping to rename a single column label with a function?


What is the required mapping to rename a column label with a string function?

e.g. this works for all columns:

df.rename(columns=str.upper)

But with

df.rename(columns={'Col 2': str.upper})

the resulting label is:

<method 'upper' of 'str' objects>

import pandas as pd
import numpy as np

n = 4
df = pd.DataFrame(np.random.randint(0, 100, size=(5, n)),
                  columns=[f'Col {i}' for i in range(n)])
renamed = df.rename(columns={'Col 2': str.upper})
print(df)
print(renamed)

Solution

  • Another possibility would be to have the list of columns that you want to change and make a dictionary with the item as upper cases. Two possibilities:

    l = ['Col 2']
    
    L = [x.upper() for x in l]
    df.rename(columns=dict(zip(l, L)))
    

    or, more elegantly, with a dictionary comprehension (see comment by mozway):

    l = ['Col 2']
    df.rename(columns={k: k.upper() for k in l})