熊猫分组并计算两列的比率

时间:2020-02-09 19:18:48

标签: python-3.x pandas pandas-groupby

我正在尝试使用Pandas和groupby来计算两列的比率。在下面的示例中,我要计算每个部门的员工状态的比例(部门中的状态数量/每个部门中的员工总数)。例如,销售部门共有3名员工,而拥有员工状态的员工人数为2,则该比例为2/3,即66.67%。我设法破解了它,但是必须有一种更优雅,更简单的方法来做到这一点。如何在下面更有效地获得所需的输出?

原始数据框架:

  Department    Name      Status
0      Sales    John    Employee
1      Sales   Steve    Employee
2      Sales    Sara  Contractor
3    Finance   Allen  Contractor
4  Marketing  Robert    Employee
5  Marketing    Lacy  Contractor

代码:

mydict ={
        'Name': ['John', 'Steve', 'Sara', 'Allen', 'Robert', 'Lacy'],
        'Department': ['Sales', 'Sales', 'Sales', 'Finance', 'Marketing', 'Marketing'],
        'Status': ['Employee', 'Employee', 'Contractor', 'Contractor', 'Employee', 'Contractor']
    }

df = pd.DataFrame(mydict)

# Create column with total number of staff Status per Department
df['total_dept'] = df.groupby(['Department'])['Name'].transform('count')
print(df)
print('\n')


# Crate column with Status ratio per department
for k, v, in df.iterrows():
    df.loc[k, 'Status_Ratio'] = (df.groupby(['Department', 'Status']).count().xs(v['Status'], level=1)['total_dept'][v['Department']]/v['total_dept']) *100
print(df)
print('\n')

# Final Groupby with Status Ratio. Size NOT needed
print(df.groupby(['Department', 'Status', 'Status_Ratio']).size())

所需的输出:

Department  Status      Status_Ratio
Finance     Contractor  100.00
Marketing   Contractor  50.00
            Employee    50.00
Sales       Contractor  33.33 
            Employee    66.67

1 个答案:

答案 0 :(得分:1)

尝试(使用原始的df):

df.groupby("Department")["Status"].value_counts(normalize=True).mul(100)

输出:

Department  Status
Finance     Contractor    100.000000
Marketing   Contractor     50.000000
            Employee       50.000000
Sales       Employee       66.666667
            Contractor     33.333333
Name: Status, dtype: float64