Để đếm quan sát, dùng groupby() rồi count() trên kết quả.
Nhập thư viện:
import pandas as pd
Tạo DataFrame:
dataFrame = pd.DataFrame({
'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],
'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],
'Quantity': [10, 50, 10, 20, 25, 50]
})
Nhóm cột trùng lặp:
group = dataFrame.groupby("Product Category")
Lấy count:
group.count()
Ví dụ
import pandas as pd
dataFrame = pd.DataFrame({
'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],
'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],
'Quantity': [10, 50, 10, 20, 25, 50]
})
print("Dataframe...\n", dataFrame)
group = dataFrame.groupby("Product Category")
print("\nResultant DataFrame...\n", group.count())
Đầu ra
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
Resultant DataFrame...
Product Name Quantity
Product Category
Computer 2 2
Electronics 2 2
Mobile Phone 2 2