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
Answers:
You can just set the columns manually by doing this
df.columns = ['b', 'a', 'TestName']
Use index.rename()
DF.set_index('b', inplace=True)
DF.index.rename('TestName', inplace=True)
DF
You can use rename_axis
:
DF.rename_axis('TestName').reset_index().set_index('b')
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 |
You can just set the columns manually by doing this
df.columns = ['b', 'a', 'TestName']
Use index.rename()
DF.set_index('b', inplace=True)
DF.index.rename('TestName', inplace=True)
DF
You can use rename_axis
:
DF.rename_axis('TestName').reset_index().set_index('b')