python pandas sort_index()方法专门用于对index排序。下面看一下具体用法:
# 指定了id列为index列
>>> df=pd.read_excel(r'D:/myExcel/1.xlsx', index_col='id')
>>> df
name score grade
id
a bog 45.0 A
c jiken 67.0 B
i bob 23.0 A
b jiken 34.0 B
g lucy NaN A
e tidy 75.0 B
1、对行index排序
# 行index升序排列
>>> df.sort_index()
name score grade
id
a bog 45.0 A
b jiken 34.0 B
c jiken 67.0 B
e tidy 75.0 B
g lucy NaN A
i bob 23.0 A
2、行index降序排列
>>> df.sort_index(ascending=False)
name score grade
id
i bob 23.0 A
g lucy NaN A
e tidy 75.0 B
c jiken 67.0 B
b jiken 34.0 B
a bog 45.0 A
3、给列index排列
>>> df.sort_index(axis=1)
grade name score
id
a A bog 45.0
c B jiken 67.0
i A bob 23.0
b B jiken 34.0
g A lucy NaN
e B tidy 75.0
哈哈,以上就是sort_index()最常见的几种方法。有兴趣欢迎关注公众号:pythonx小工具。一起学习python和pandas