程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Pandas Groupby return incremental numbers of groups as new column

发布于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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

29 0
收藏该文
已收藏

评论内容:(最多支持255个字符)