首页 > 解决方案 > 按颜色分组,按 b 求和,然后按 a/b 并为新计算创建一个新列。我下面的代码显示新计算列的输出是错误的

问题描述

color  a    b
blue   100  25
blue   200  10
blue   450  50
red    60   2
red    75   3
red    80   4
orange 125  5
orange 90   9
orange 36   4

我试过了

def x():

    getcal=df['a']/df['b']
    df["new calculation"]=getcal 
    trythis=df[["color", "a", "b", "new calculation"]]
    final = trythis.groupby(by = "color").sum().sort_values(by="b")
    print(final)

x()

标签: pythonpandas

解决方案


我认为你需要:

df = (df.groupby('color', as_index=False)['a','b']
        .sum()
        .assign(calculation=lambda x: x.a / x.b)
        .sort_values(by="b"))
print (df)
    color    a   b  calculation
2     red  215   9    23.888889
1  orange  251  18    13.944444
0    blue  750  85     8.823529

推荐阅读