How to rename the first column of a pandas dataframe?

Viewed 1795

I have come across this question many a times over internet however not many answers are there except for few of the likes of the following:

Cannot rename the first column in pandas DataFrame

I approached the same using following:

df = df.rename(columns={df.columns[0]: 'Column1'})

Is there a better or cleaner way of doing the rename of the first column of a pandas dataframe? Or any specific column number?

2 Answers

You're already using a cleaner way in pandas.

It is sad that:

df.columns[0] = 'Column1'

Is impossible because Index objects do not support mutable assignments. It would give an TypeError.

You still could do iterable unpacking:

df.columns = ['Column1', *df.columns[1:]]

Or:

df = df.set_axis(['Column1', *df.columns[1:]], axis=1)

Not sure if cleaner, but possible idea is convert to list and set by indexing new value:

df = pd.DataFrame(columns=[4,7,0,2])

arr = df.columns.tolist()
arr[0] = 'Column1'
df.columns = arr


print (df)
Empty DataFrame
Columns: [Column1, 7, 0, 2]
Index: []
Related