Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Trả về chỉ số nguyên (integer indices) để sắp xếp Index

Để trả về các chỉ số nguyên (integer indices) mà nếu áp dụng sẽ sắp xếp Index, sử dụng phương thức index.argsort() trong Pandas.

Các bước thực hiện

  1. Import thư viện: import pandas as pd
  2. Tạo Index chuỗi: index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name='Products')
  3. Gọi index.argsort().

Ví dụ hoàn chỉnh

import pandas as pd

index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name='Products')
print("Pandas Index...\n", index)
print("\nNumber of elements in the index...\n", index.size)
print("\nThe dtype object...\n", index.dtype)

res = index.argsort()
print("\nThe integer indices to sort the index...\n", res)
print("\nOrdered..\n", index[res])

Kết quả

Pandas Index...
 Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Number of elements in the index...
 5
The dtype object... object
The integer indices to sort the index...
 [1 3 2 0 4]
Ordered..
 Index(['Accessories', 'Books', 'Decor', 'Electronics', 'Toys'], dtype='object', name='Products')

Giải thích: argsort() trả về mảng chỉ số: [1, 3, 2, 0, 4]. Áp dụng lên index gốc cho Index đã sắp xếp theo thứ tự bảng chữ cái: Accessories, Books, Decor, Electronics, Toys.