Using df.columns =[columns], I can change the name of all columns of a DataFrame, but not some specific columns. I want to rename a couple of columns. How can I do that?
You can use the rename() function of Pandas. You need to pass a dictionary having the old name as the key and the new name as the value to this function. Here is an example to use this function in different ways:
>>> import numpy as np>>> import pandas as pd>>> df = pd.DataFrame({'id1':[1,2,3,4,5,6,7,8,9,10],'class':['pos','pos','neg','pos','neg','neg','pos','neg','neg','pos']})>>> df id1 class0 1 pos1 2 pos2 3 neg3 4 pos4 5 neg5 6 neg6 7 pos7 8 neg8 9 neg9 10 pos>>> df1=df.rename(columns={"id1":"protein_id"})>>> df1 protein_id class0 1 pos1 2 pos2 3 neg3 4 pos4 5 neg5 6 neg6 7 pos7 8 neg8 9 neg9 10 pos>>> df2=df.rename({"id1":"protein_id"}, axis=1)>>> df2 protein_id class0 1 pos1 2 pos2 3 neg3 4 pos4 5 neg5 6 neg6 7 pos7 8 neg8 9 neg9 10 pos>>> df3=df.rename({"id1":"protein_id"}, axis='columns')>>> df3 protein_id class0 1 pos1 2 pos2 3 neg3 4 pos4 5 neg5 6 neg6 7 pos7 8 neg8 9 neg9 10 pos