Mô tả bài toán
Cho Series chuỗi:
0 abdef 1 ijkl 2 Abdef 3 oUijl
Yêu cầu: Sắp xếp giảm dần (descending). Kết quả:
3 oUijl 1 ijkl 0 abdef 2 Abdef
Giải pháp
Sử dụng sort_values(ascending=False). Sắp xếp mặc định của Python là theo mã ASCII (chữ hoa trước chữ thường).
Ví dụ code hoàn chỉnh
import pandas as pd
l = ["abdef","ijkl","Abdef","oUijl"]
data = pd.Series(l)
print("Series gốc:")
print(data)
sorted_desc = data.sort_values(ascending=False)
print("\nSắp xếp giảm dần:")
print(sorted_desc)
# So sánh: sắp xếp tăng dần
print("\nSắp xếp tăng dần (ascending=True):")
print(data.sort_values(ascending=True))
Đầu ra
Series gốc: 0 abdef 1 ijkl 2 Abdef 3 oUijl dtype: object Sắp xếp giảm dần: 3 oUijl 1 ijkl 0 abdef 2 Abdef dtype: object Sắp xếp tăng dần: 2 Abdef 0 abdef 1 ijkl 3 oUijl dtype: object
Giải thích thứ tự ASCII
- Chữ hoa (A-Z): mã 65-90
- Chữ thường (a-z): mã 97-122
- Do đó 'A' < 'a', nên "Abdef" đứng trước "abdef" khi tăng dần.
Sắp xếp không phân biệt chữ hoa/thường
# Sắp xếp case-insensitive
sorted_ci = data.sort_values(key=lambda s: s.str.lower(), ascending=False)
print("\nGiảm dần không phân biệt hoa/thường:")
print(sorted_ci)
Giảm dần không phân biệt hoa/thường: 3 oUijl 1 ijkl 0 abdef 2 Abdef