Python Pandas DataFrame如何按x_closest_autobahn分组生成升序排名新列
Pandas 分组内升序排名实现方案
核心实现代码
# 按分组字段、组内排序字段完成全局排序 df = df.sort_values( by=["x_closest_autobahn", "order_numbers"], ascending=[True, True] ) # 按分组维度生成组内升序排名,转换为整数类型 # method="first" 会按当前排序顺序分配连续整数排名,避免同值导致的序号跳空 df["order_number_autobahn_x"] = df.groupby("x_closest_autobahn")["order_numbers"].rank( method="first", ascending=True ).astype(int) # 如需还原为无冗余索引的规整结构,可执行重置索引 df = df.reset_index(drop=True)
原尝试方案的问题说明
- 硬编码筛选
x_closest_autobahn ==3的单组数据,无法覆盖全部分组场景,不具备通用性 - 全局排序后重置索引生成的是全局序号,没有绑定分组维度,无法实现组内独立排名的需求
- 排序操作带
inplace=True参数时会返回None,搭配多余的列表嵌套结构给新列赋值,最终会得到空值结果
最终输出效果匹配
| 行索引 | order_numbers | x_closest_autobahn | order_number_autobahn_x |
|---|---|---|---|
| 0 | 5 | 3 | 1 |
| 1 | 11 | 3 | 2 |
| 2 | 34 | 3 | 3 |
| 3 | 2 | 12 | 1 |
| 4 | 8 | 12 | 2 |
内容的提问来源于stack exchange,提问作者Johanna Marklund
相关产品推荐
相关产品推荐

