How to rename the first column of a pandas dataframe?

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?

Upvotes: 10

Views: 7502

Answers (3)

kobotschick
kobotschick

Reputation: 19

As as a one liner

df.columns.values[0] = 'Column1'

Upvotes: 1

jezrael
jezrael

Reputation: 863631

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: []

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71610

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)

Upvotes: 7

Related Questions