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

Python Pandas - Trả về bản sao Index đã sắp xếp theo thứ tự giảm dần

Để trả về bản sao của Index đã sắp xếp theo thứ tự giảm dần (descending), sử dụng phương thức index.sort_values() với tham số ascending=False.

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

  1. Import thư viện: import pandas as pd
  2. Tạo Index: index = pd.Index([50, 10, 70, 95, 110, 90, 30])
  3. Gọi index.sort_values(ascending=False).

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)
print("\nThe dtype object...\n", index.dtype)

# Sắp xếp giảm dần
print("\nSort the index values in descending order...\n", index.sort_values(ascending=False))

Kết quả

Pandas Index...
 Int64Index([50, 10, 70, 95, 110, 90, 30], dtype='int64')
Number of elements in the index...
 7
The dtype object... int64
Sort the index values in descending order...
 Int64Index([110, 95, 90, 70, 50, 30, 10], dtype='int64')