Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 664
JALO - JusAnotherLivngOrganism Avatar asked Sep 14 '21 07:09

JALO - JusAnotherLivngOrganism


People also ask

How do I change the first column name in Python?

You can change the column name of pandas DataFrame by using DataFrame. rename() method and DataFrame. columns() method.

How do I rename a column name in Pandas?

One way of renaming the columns in a Pandas Dataframe is by using the rename() function.


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)
like image 149
U12-Forward Avatar answered Oct 20 '22 14:10

U12-Forward


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: []
like image 30
jezrael Avatar answered Oct 20 '22 12:10

jezrael