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)
对索引值进行排序。默认为升序排列。使用值设为 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 # Creating Pandas index index = pd.Index([50, 10, 70, 95, 110, 90, 30]) # Display the Pandas index print("Pandas Index...\n",index) # Return the number of elements in the Index print("\nNumber of elements in the index...\n",index.size) # Sort index values # By default, sorts in Ascending order # 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))
广告