Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename Dataframe column based on column index

Tags:

python

pandas

Is there a built in function to rename a pandas dataframe by index?

I thought I knew the name of my column headers, but it turns out the second column has some hexadecimal characters in it. I will likely come across this issue with column 2 in the future based on the way I receive my data, so I cannot hard code those specific hex characters into a dataframe.rename() call.

Is there a function that would be appropriately named rename_col_by_index() that I have not been able to find?

Ex:

>>> df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
>>> df.rename_col_by_index(1, 'new_name')
>>> df
   a  new_name
0  1         3
1  2         4
like image 270
aberger Avatar asked Jan 16 '17 22:01

aberger


2 Answers

@MaxU's answer is better

df.rename(columns={"col1": "New name"})

More in docs

like image 144
taoufik A Avatar answered Sep 23 '22 06:09

taoufik A


UPDATE: thanks to @Vincenzzzochi:

In [138]: df.rename(columns={df.columns[1]: 'new'})
Out[138]:
   a  new  c
0  1    3  5
1  2    4  6

In [140]: df
Out[140]:
   a  b  c
0  1  3  5
1  2  4  6

or bit more flexible:

In [141]: mapping = {df.columns[0]:'new0', df.columns[1]: 'new1'}

In [142]: df.rename(columns=mapping)
Out[142]:
   new0  new1  c
0     1     3  5
1     2     4  6
like image 44
MaxU - stop WAR against UA Avatar answered Sep 22 '22 06:09

MaxU - stop WAR against UA