简体   繁体   English

如何在熊猫中分组和计算

[英]How to group and calculate in pandas

I have df like below我有如下 df

customer class  score
A          a      10
A          b      20
B          a      40
B          b      50

I would like to group, transform and calculate like this.我想像这样分组,转换和计算。

customer  score(b-a)
A           10
B           10

I couldnt figure out how to calculate..我不知道如何计算..

df.groupby(df.customer)

If someone has experienced such aggregation,please let me know.如果有人经历过这样的聚合,请告诉我。

Thanks谢谢

You can use @HenryYik's comment, or you can use pivot :您可以使用@HenryYik 的评论,也可以使用pivot

(df.pivot(index='customer', columns='class', values='score')
   .assign(score=lambda x: x['b']-x['a'])
)

Output:输出:

class      a   b  score
customer               
A         10  20     10
B         40  50     10

Alternative solution, group by over customer and apply a custom function替代解决方案,按客户分组并应用自定义功能

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)

This will result in expected answer.这将导致预期的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM