You need to enable JavaScript to run this app. Python Pandas DataFrame如何按x_closest_autobahn分组生成升序排名新列
优惠活动
大模型
产品
解决方案
定价
更多

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_numbersx_closest_autobahnorder_number_autobahn_x
0531
11132
23433
32121
48122

内容的提问来源于stack exchange,提问作者Johanna Marklund

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.03 15:15:10