简体   繁体   中英

Add a name to pandas dataframe index

数据例证

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM