Để sắp xếp giá trị Index và đồng thời trả về các chỉ số (indices) mà nếu áp dụng sẽ sắp xếp Index, sử dụng phương thức index.sort_values() với tham số return_indexer=True.
Các bước thực hiện
- Import thư viện:
import pandas as pd - Tạo Index:
index = pd.Index([50, 10, 70, 95, 110, 90, 30]) - Gọi
index.sort_values(return_indexer=True).
Ví dụ hoàn chỉnh
import pandas as pd
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
print("Pandas Index...\n", index)
print("\nNumber of elements in the index...\n", index.size)
# Sắp xếp và trả về cả indexer
print("\nSort and also return the indices that would sort the index...\n", index.sort_values(return_indexer=True))
Kết quả
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))
Giải thích: Trả về một tuple: (Index đã sắp xếp, mảng indexer). Indexer [1, 6, 0, 2, 5, 3, 4] nghĩa là: phần tử nhỏ nhất ở vị trí 1 (giá trị 10), tiếp theo vị trí 6 (giá trị 30), vị trí 0 (giá trị 50), v.v.