发布于2025-01-05 08:57 阅读(115) 评论(0) 点赞(29) 收藏(3)
Original DF
| performance | driver_id | season |
|-------------|-----------|--------|
| 1 | 1 | 17 |
| 2 | 1 | 17 |
| 3 | 2 | 17 |
| 4 | 2 | 18 |
| 5 | 2 | 18 |
| 6 | 2 | 19 |
| 7 | 1 | 17 |
| 8 | 1 | 18 |
| 9 | 1 | 18 |
Desired DF
| performance | driver_id | season | season_order |
|-------------|-----------|--------|--------------|
| 1 | 1 | 17 | 1 |
| 2 | 1 | 17 | 1 |
| 3 | 2 | 17 | 1 |
| 4 | 2 | 18 | 2 |
| 5 | 2 | 18 | 2 |
| 6 | 2 | 19 | 3 |
| 7 | 1 | 17 | 1 |
| 8 | 1 | 18 | 2 |
| 9 | 1 | 18 | 2 |
I have a DF where I want to set drivers performances as either first, second, third seasons etc. but this must be differnet for a given driver.
I have tried using cumsum
and rank
but only help within groups I want between groups ordering/ranking. These methods seem to work better for single column groupbys from my experimenting.
df["season_number"] = (df
.groupby(["driver_id ", "season"])
.season
.transform("rank")
)
I think you need GroupBy.rank
:
df["season_number"] = df.groupby("driver_id").season.rank(method='dense').astype(int)
print (df)
performance driver_id season season_number
0 1 1 17 1
1 2 1 17 1
2 3 2 17 1
3 4 2 18 2
4 5 2 18 2
5 6 2 19 3
6 7 1 17 1
7 8 1 18 2
8 9 1 18 2
作者:黑洞官方问答小能手
链接:https://www.pythonheidong.com/blog/article/2046771/febb0a03e50872b9c58c/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!