Change index of a pandas data frame

Question:

I have the following DF

a b
Test1 2 1
Test2 3 2

What I currently do is the following :

DF.reset_index().set_index('b')

which give the following output :

b a index
1 2 Test1
2 3 Test2

But what if I don’t want the column to be named as "index" ?

For example I wish to have the following output : (Replace "index" by "TestName")

b a TestName
1 2 Test1
2 3 Test2
Asked By: TourEiffel

||

Answers:

You can just set the columns manually by doing this

df.columns = ['b', 'a', 'TestName']
Answered By: Moro Wenka

Use index.rename()

DF.set_index('b', inplace=True)
DF.index.rename('TestName', inplace=True)
DF
Answered By: Naveed

You can use rename_axis:

DF.rename_axis('TestName').reset_index().set_index('b')
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.