3

data exmple

As the picture shows , how can I add a name to index in pandas dataframe?And when added it should be like this: picture

1 Answer 1

10

You need set index name:

df.index.name = 'code'

Or rename_axis:

df = df.rename_axis('code')

Sample:

np.random.seed(100)
df = pd.DataFrame(np.random.randint(10,size=(5,5)),columns=list('ABCDE'),index=list('abcde'))
print (df)
   A  B  C  D  E
a  8  8  3  7  7
b  0  4  2  5  2
c  2  2  1  0  8
d  4  0  9  6  2
e  4  1  5  3  4

df.index.name = 'code'
print (df)
      A  B  C  D  E
code               
a     8  8  3  7  7
b     0  4  2  5  2
c     2  2  1  0  8
d     4  0  9  6  2
e     4  1  5  3  4
df = df.rename_axis('code')
print (df)

      A  B  C  D  E
code               
a     8  8  3  7  7
b     0  4  2  5  2
c     2  2  1  0  8
d     4  0  9  6  2
e     4  1  5  3  4
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much! It's helpful!
Small advice to future - don't post images of code (or links to them). Good luck!
Thank you! I got it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.