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))

更新於: 14-Oct-2021

224 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.