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

Cách nhóm đếm giá trị (Groupby value counts) trên Pandas DataFrame

Để đếm số lần xuất hiện của từng tổ hợp giá trị trên nhiều cột, dùng groupby, size và unstack.

Ví dụ

Mã hoàn chỉnh:

import pandas as pd

dataFrame = pd.DataFrame({
    'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],
    'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],
    'Quantity': [10, 50, 10, 20, 25, 50]
})
print("DataFrame gốc:")
print(dataFrame)

result = dataFrame.groupby(['Product Category', 'Product Name', 'Quantity']).size().unstack(fill_value=0)
print("\nKết quả groupby count unstack:")
print(result)

Kết quả

DataFrame gốc:
  Product Category   Product Name  Quantity
0         Computer      Keyboard        10
1     Mobile Phone      Charger        50
2      Electronics      SmartTV        10
3      Electronics       Camera        20
4         Computer  Graphic Card        25
5     Mobile Phone     Earphone        50

Kết quả groupby count unstack:
Quantity                          10  20  25  50
Product Category Product Name
Computer         Graphic Card       0   0   1   0
                 Keyboard           1   0   0   0
Electronics      Camera              0   1   0   0
                 SmartTV             1   0   0   0
Mobile Phone     Charger             0   0   0   1
                 Earphone            0   0   0   1

Giải thích

  • Tạo DataFrame mẫu.
  • groupby([...]).size() đếm tần suất mỗi nhóm.
  • unstack(fill_value=0) chuyển cấp cuối của index thành cột, điền 0 cho thiếu.