Để nhóm DataFrame trong Pandas, ta dùng groupby(). Để sắp xếp DataFrame đã nhóm theo thứ tự tăng dần, sử dụng sort_values() với tham số ascending=True. Phương thức size() trả về kích thước của từng nhóm.
Cú pháp sắp xếp tăng dần
dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)
Ví dụ hoàn chỉnh
import pandas as pd
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
"Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
})
print("DataFrame...\n", dataFrame)
# Nhóm theo cột Reg_Price và sắp xếp tăng dần
print("\nSắp xếp theo thứ tự tăng dần...")
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=True))
Kết quả
DataFrame...
Car Reg_Price
0 BMW 1000
1 Lexus 1400
2 Audi 1000
3 Mercedes 900
4 Jaguar 1700
5 Bentley 900
Sắp xếp theo thứ tự tăng dần...
Reg_Price
1400 1
1700 1
900 2
1000 2
dtype: int64
Kết quả cho thấy các mức giá (Reg_Price) được sắp xếp theo số lượng xuất hiện từ ít đến nhiều.