I was looking for an elegant way to change a specified column name in a DataFrame.

play data …

import pandas as pd
d = {
         'one': [1, 2, 3, 4, 5],
         'two': [9, 8, 7, 6, 5],
         'three': ['a', 'b', 'c', 'd', 'e']
    }
df = pd.DataFrame(d)

The most elegant solution I have found so far …

names = df.columns.tolist()
names[names.index('two')] = 'new_name'
df.columns = names

I was hoping for a simple one-liner … this attempt failed …

df.columns[df.columns.tolist().index('one')] = 'another_name'

Any hints gratefully received.

10 Answers
10

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *