Python Pandas - 对索引值进行排序并返回对索引进行排序的索引
要对索引值进行排序并返回对索引进行排序的索引,请使用.该return_indexer参数被设置为真。index.sort_values()
首先,导入所需的库-
import pandas as pd
创建熊猫索引-
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
显示熊猫指数-
print("Pandas Index...\n",index)
排序索引值。默认情况下,按升序排序。使用值为True的“return_indexer”参数返回索引以对索引进行排序-
print("\nSort and also return the indices that would sort the index...\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("\nNumber of elements in the index...\n",index.size) #排序索引值 #默认情况下,按升序排序 # Return the indices to sort the index using the "return_indexer" parameter with value True print("\nSort and also return the indices that would sort the index...\n",index.sort_values(return_indexer=True))输出结果
这将产生以下输出-
Pandas Index... Int64Index([50, 10, 70, 95, 110, 90, 30], dtype='int64') Number of elements in the index... 7 Sort and also return the indices that would sort the index... (Int64Index([10, 30, 50, 70, 90, 95, 110], dtype='int64'), array([1, 6, 0, 2, 5, 3, 4], dtype=int64))