Mapping to rename a single column label with a function?

62 views Asked by At

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)
2

There are 2 answers

2
nemo On BEST ANSWER

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})
0
mozway On

You can't pass a function as dictionary item. This is actually quite logic, since the key is a column name it assumes you already know this name and thus could craft the expected value.

Thus you should use:

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

If you know the value can be in a list/set of values you could also use a custom function:

def renamer(col):
    if col in {'Col 2'}:
        return col.upper()
    return col

df.rename(columns=renamer)

Output:

   Col 0  Col 1  COL 2  Col 3
0     18     79      5     79
1     70     43     22     47
2     43      0     79     28
3      7     10     97     49
4     97     16     44      9