按升序对索引进行排序 – Python Pandas

sort_index()用于排序索引在升序和降序。如果您不提及任何参数,则索引按升序排序。

首先,导入所需的库 -

import pandas as pd

创建一个新的数据帧。它有未排序的索引 -

dataFrame = pd.DataFrame([100, 150, 200, 250, 250, 500],index=[4, 8, 2, 9, 15, 11],columns=['Col1'])

对索引进行排序 -

dataFrame.sort_index()

示例

以下是代码 -

import pandas as pd

dataFrame = pd.DataFrame([100, 150, 200, 250, 250, 500],index=[4, 8, 2, 9, 15, 11],columns=['Col1'])

print"DataFrame...\n",dataFrame

print"\nSort index...\n",dataFrame.sort_index()
输出结果

这将产生以下输出 -

DataFrame...
   Col1
4   100
8   150
2   200
9   250
15  250
11  500

Sort index...
   Col1
2   200
4   100
8   150
9   250
11  500
15  250