You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中为有序DataFrame映射上层分组ID?

为有序DataFrame添加上层分组ID列

现有一个有序的DataFrame df,结构如下:

Level    ID
5        A
8        DD
8        DA
8        AC
5        B
8        BA
8        BB
8        BC
8        BD

需求说明

为每行添加Upper_ID列,规则如下:

  • Level为5的行,其Upper_ID等于自身的ID
  • Level为5的行作为下方Level为8的行的上层组,该行ID会作为后续所有Level=8行的Upper_ID,直到下一个Level=5的行出现

期望得到的结果:

Level    ID   Upper_ID
5        A       A
8        DD      A
8        DA      A
8        AC      A
5        B       B
8        BA      B
8        BB      B
8        BC      B
8        BD      B

实现方案

利用Pandas的loc筛选和ffill()向前填充方法即可完成,代码如下:

import pandas as pd

# 构造示例DataFrame(如果已有df可跳过此步骤)
data = {
    'Level': [5, 8, 8, 8, 5, 8, 8, 8, 8],
    'ID': ['A', 'DD', 'DA', 'AC', 'B', 'BA', 'BB', 'BC', 'BD']
}
df = pd.DataFrame(data)

# 生成Upper_ID列
df['Upper_ID'] = df.loc[df['Level'] == 5, 'ID'].ffill()

代码解释

  1. df.loc[df['Level'] == 5, 'ID']:筛选出所有Level为5的行的ID值,其余位置填充为NaN
  2. ffill():将NaN值替换为最近的非NaN值,实现把每个Level=5的ID传递给后续所有Level=8的行,直到下一个Level=5的行出现
  3. Level为5的行本身的ID会被保留,因此其Upper_ID自然等于自身ID,符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:54:53