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

Python Pandas - Đếm số hàng trong mỗi nhóm (Group Size)


Sử dụng groupby() theo một hoặc nhiều cột, sau đó gọi size() để đếm số hàng trong mỗi nhóm.

Import và tạo DataFrame:

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

Gom nhóm và đếm:

new_group = dataFrame.groupby(["Product Category", "Quantity"]).size()

Ví dụ hoàn chỉnh

import pandas as pd
dataFrame = pd.DataFrame({
    'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],
    'Quantity': [10, 50, 10, 20, 25, 50],
    'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone']
})
print("Dataframe...\n", dataFrame)
new_group = dataFrame.groupby(["Product Category", "Quantity"]).size()
print("\nUpdated Dataframe...\n", new_group)

Kết quả

Dataframe...
  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
Updated Dataframe...
Product Category  Quantity
Computer          10           1
                  25           1
Electronics       10           1
                  20           1
Mobile Phone      50           2
dtype: int64