为了账号安全,请及时绑定邮箱和手机立即绑定

如何在熊猫中分组和计算

如何在熊猫中分组和计算

DIEA 2022-08-02 17:19:14
我有df如下customer class  scoreA          a      10A          b      20B          a      40B          b      50我想像这样分组,转换和计算。customer  score(b-a)A           10B           10我不知道如何计算。df.groupby(df.customer)如果有人经历过这样的聚合,请告诉我。谢谢
查看完整描述

2 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

您可以使用@HenryYik的评论,也可以使用:pivot


(df.pivot(index='customer', columns='class', values='score')

   .assign(score=lambda x: x['b']-x['a'])

)

输出:


class      a   b  score

customer               

A         10  20     10

B         40  50     10


查看完整回答
反对 回复 2022-08-02
?
慕虎7371278

TA贡献1802条经验 获得超4个赞

替代解决方案,按客户分组并应用自定义功能


def get_score(temp):

    map_score = dict(zip(temp['class'], temp['score'])) # mapping of class and score for each customer

    return map_score['b'] - map_score['a']

df.groupby("customer").apply(get_score)

这将导致预期的答案。


查看完整回答
反对 回复 2022-08-02
  • 2 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信