python - 按颜色分组,按 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()
解决方案
我认为你需要:
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
推荐阅读
- css - CSS Grid 自动适应最大内容
- php - PHP require_once 仍然需要多次
- linux - PS1没有设置颜色
- c# - 如何从 Stream 创建 IMediaPlaybackSource,以便在不使用过时的 SetStreamSource 方法的情况下设置 MediaPlayer 源?
- common-lisp - 如何在 sbcl 中找到外星结构的大小?
- javascript - 自动单选按钮选择
- javascript - React - 在默认值更改时执行一个函数
- sql - where 子句中的 case 语句中使用的输入参数
- python - 在 Python 中掷 2 个骰子,如果它们是相同的数字,再掷一次,然后继续
- typescript - Firestore 批量删除