Python Pandas – 对索引值进行排序并返回对索引进行排序的索引
要对索引值进行排序并返回对索引进行排序的索引,请使用 index.sort_values() 。参数 return_indexer 被设置为 True 。
首先,导入所需的库 −
import pandas as pd
创建 Pandas 索引 −
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
显示 Pandas 的索引 −
print("Pandas Index...\n",index)
对索引值进行排序。默认情况下,按升序排序。使用 “return_indexer” 参数指定要返回对索引进行排序的索引值,值为 True −
print("\n对索引进行排序并返回对索引进行排序的索引...\n",index.sort_values(return_indexer=True))
示例
以下是代码 −
import pandas as pd
# 创建 Pandas 索引
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
# 显示 Pandas 的索引
print("Pandas Index...\n",index)
# 返回索引的元素数
print("\n索引中的元素数...\n",index.size)
# 对索引值进行排序
# 默认情况下,按升序排序
# 使用 "return_indexer" 参数指定要返回对索引进行排序的索引值,值为 True
print("\n对索引进行排序并返回对索引进行排序的索引...\n",index.sort_values(return_indexer=True))
输出
这将产生以下输出 −
Pandas Index...
Int64Index([50, 10, 70, 95, 110, 90, 30], dtype='int64')
索引中的元素数...
7
对索引进行排序并返回对索引进行排序的索引...
(Int64Index([10, 30, 50, 70, 90, 95, 110], dtype='int64'), array([1, 6, 0, 2, 5, 3, 4], dtype=int64))