user6007834
user6007834

Reputation: 83

Add a name to pandas dataframe index

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

Upvotes: 3

Views: 5983

Answers (1)

jezrael
jezrael

Reputation: 862641

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

Upvotes: 10

Related Questions