Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column names in Pandas Dataframe from a list

Tags:

python

pandas

Is is possible to change Column Names using data in a list?

df = pd.DataFrame([[1, 1.0, 2.3,0.2,0.53], [2, 3.35, 2.0,0.2,0.65], [2,3.4, 
       2.0,0.25,0.55], [3,3.4,2.0,0.25,0.55], [1,3.4,2.0,0.25,0.55], 
       [3,3.4,2.0,0.25,0.55]], 
       columns=["ID", "A", "B","C","D"])\
       .set_index('ID')

I have my new labels as below:

New_Labels=['NaU', 'MgU', 'AlU', 'SiU']

Is possible to change the names using data in the above list? My original data set has 100 columns and I did not want to do it manually for each column.

I was trying the following using df.rename but keep getting errors. Thanks!

like image 807
Suresh Raja Avatar asked Aug 02 '17 18:08

Suresh Raja


4 Answers

You can use this :

df.columns = New_Labels
like image 127
Spandan Brahmbhatt Avatar answered Nov 15 '22 07:11

Spandan Brahmbhatt


Using rename is a formally more correct approach. You just have to provide a dictionary that maps your current columns names to the new ones (thing that will guarantee expected results even in case of misplaced columns)

new_names = {'A':'NaU', 'B':'MgU', 'C':'Alu', 'D':'SiU'}
df.rename(index=str, columns=new_names)

Notice you can provide entries for the sole names you want to substitute, the rest will remain the same.

like image 39
5agado Avatar answered Nov 15 '22 07:11

5agado


df = pd.DataFrame([[1, 1.0, 2.3,0.2,0.53], [2, 3.35, 2.0,0.2,0.65], [2,3.4, 
       2.0,0.25,0.55], [3,3.4,2.0,0.25,0.55], [1,3.4,2.0,0.25,0.55], 
       [3,3.4,2.0,0.25,0.55]], 
       columns=["ID", "A", "B","C","D"])\
       .set_index('ID')
New_Labels=['NaU', 'MgU', 'AlU', 'SiU']
df.columns = New_Labels

this will make df look like this:

     NaU  MgU   AlU   SiU
ID                       
1   1.00  2.3  0.20  0.53
2   3.35  2.0  0.20  0.65
2   3.40  2.0  0.25  0.55
3   3.40  2.0  0.25  0.55
1   3.40  2.0  0.25  0.55
3   3.40  2.0  0.25  0.55
like image 41
jacoblaw Avatar answered Nov 15 '22 08:11

jacoblaw


df.columns = New_Labels

Take care of the sequence of new column names.

like image 22
Neo Avatar answered Nov 15 '22 09:11

Neo