首页 > 解决方案 > 向 lambda 或函数添加计算

问题描述

我有一个df,例如

    ID |    Status   | Color
   555    Cancelled     Green
   434    Processed     Red   
   212    Cancelled     Blue
   121    Cancelled     Green
   242    Cancelled     Blue
   352    Processed     Green
   343    Processed     Blue

我正在使用如下代码:

cc = df.groupby(by='Color').ID.count()
df.groupby(by=['Color', 'Status']).apply(lambda x: len(x)/cc.loc[x.Color.iloc[0]])

这给了我输出,例如

Color     Status   
Blue   Cancelled    0.666667
       Processed    0.333333
Green  Cancelled    0.666667
       Processed    0.333333
Red    Processed    1.000000
dtype: float64

这给了我每种颜色状态的百分比。

还有一个名为Dollar_value的字段,其中每行包含美元金额,如果我想在我的输出中添加两个字段1. Total_Dollars表示该颜色和状态,2. Dollar_per_order表示该颜色(这意味着如果 Total_Dollars 是 1000 并且存在该颜色和状态是 200 行,它将是 1000/200 或 5。我可以轻松地将这两个计算添加到我已经拥有的输出中吗?或者我需要创建一个函数吗?

期望的输出:

    Color     Status              Total |Dollar_Per_Order                
    Blue   Cancelled    0.666667  1000       20
           Processed    0.333333  200        5
    Green  Cancelled    0.666667  2000       20
           Processed    0.333333  1000       5
    Red    Processed    1.000000  300        10
    dtype: float64

谢谢!

标签: pythonpython-3.xpandasdata-science

解决方案


要计算所有 3 列,请将要应用于每个组的函数定义为:

def fn(grp):
    total = grp.dollar_value.sum()
    rowNo = len(grp.index)
    return pd.Series([ rowNo/cc[grp.name[0]], total, total/rowNo ],
        index=[ 'Percentage', 'Total_Dollars', 'Dollar_per_order'])

然后应用它:

df.groupby(by=['Color', 'Status']).apply(fn)

请注意,我使用len(grp.index)而不是len(grp). 原因是它运行得更快一些。

除了你之外,我还以其他方式阅读当前组的颜色


推荐阅读