Computer >> Máy Tính >  >> Lập trình >> Python

Cách tính các giá trị theo nhóm trên Pandas DataFrame

Để đếm giá trị Groupby, hãy sử dụng các phương thức groupby (), size () và unack () của Pandas DataFrame. Đầu tiên, hãy tạo DataFrame có 3 cột -

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]})

Bây giờ, các giá trị theo nhóm được tính bằng phương thức groupby (). Để đếm, hãy sử dụng size () và unack (). Unack () cung cấp một cấp nhãn cột mới -

dataFrame = dataFrame.groupby(['Product Category', 'Product Name', 'Quantity']).size().unstack(fill_value=0)

Ví dụ

Sau đây là mã hoàn chỉnh -

import pandas as pd

# create a dataframe with 3 columns
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]})

# dataframe
print"Dataframe...\n",dataFrame

# count and unstack
dataFrame = dataFrame.groupby(['Product Category', 'Product Name', 'Quantity']).size().unstack(fill_value=0)

print"\nResultant DataFrame...\n",dataFrame

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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...
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