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

如何为父子关系生成按父级划分的索引数组?

为父级分组下的唯一父子关系生成索引

以下是几种常用工具的实现方案,均能满足你“为每个父级下的唯一父子关系分配从1开始的连续索引,重复关系共享同一索引”的需求:

SQL 实现

使用窗口函数 DENSE_RANK(),按Parent分区、Child排序,即可生成目标索引:

SELECT 
    Child,
    Parent,
    DENSE_RANK() OVER (PARTITION BY Parent ORDER BY Child) AS Index
FROM your_table;

该查询会为每个Parent分组内的不同Child分配连续编号,重复的父子关系会得到相同的索引值,完全匹配你需要的结果。

Python Pandas 实现

通过groupby结合rank方法,指定method='dense'生成连续不跳号的索引:

import pandas as pd

# 加载示例数据(实际场景可替换为你的数据源)
data = {
    'Child': ['Child A1', 'Child A2', 'Child A3', 'Child A3', 'Child A2', 'Child A2',
              'Child B1', 'Child B1', 'Child B2', 'Child B3', 'Child B2', 'Child B3'],
    'Parent': ['Parent A']*6 + ['Parent B']*6
}
df = pd.DataFrame(data)

# 生成索引
df['Index'] = df.groupby('Parent')['Child'].rank(method='dense', ascending=True).astype(int)

# 输出结果
print(df)

运行后会输出带目标索引的数据集,method='dense'确保同一父级下相同子项的索引一致,且索引从1开始连续递增。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:03:30