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

Python如何实现Pandas DataFrame中连续位置单词的分组实体标注

实现方案

核心思路

  • 先编写辅助函数将离散的位置索引转换为连续区间,例如将[6,7,8]转换为[(6,8)],非连续的位置如[2,4,5,7]转换为[(2,2), (4,5), (7,7)]
  • 对每一行文本先拆分单词列表,按从后往前的顺序处理所有标注区间,避免前面的修改影响后续区间的索引
  • 连续区间的单词合并后统一套标签,单个位置的区间正常标注即可

完整可运行代码

import pandas as pd

# 辅助函数:将位置列表转换为连续区间
def get_continuous_ranges(pos_list):
    if not pos_list:
        return []
    pos_list = sorted(pos_list)
    ranges = []
    start = pos_list[0]
    end = pos_list[0]
    for pos in pos_list[1:]:
        if pos == end + 1:
            end = pos
        else:
            ranges.append((start, end))
            start = pos
            end = pos
    ranges.append((start, end))
    return ranges

# 原始数据
data = {'text': ['This is an example text that I use in order to get an answer',
                 'Discussion: We are examining the possibility of this solution'],
        'in': [[2], [3]],
        'tar': [[6], [6, 7, 8]]}
df = pd.DataFrame(data)
cols = df.columns[1:]  # 获取需要标注的列:in、tar

new_text = []
for idx, row in df.iterrows():
    words = row['text'].split()
    # 收集所有需要标注的区间:(起始位置, 结束位置, 标签名)
    all_ranges = []
    for col in cols:
        ranges = get_continuous_ranges(row[col])
        for s, e in ranges:
            all_ranges.append((s, e, col.upper()))
    # 按结束位置倒序排序,避免修改前面的内容影响后续区间索引
    all_ranges.sort(key=lambda x: -x[1])
    for s, e, tag in all_ranges:
        # 合并区间内的单词,套标签
        merged_content = ' '.join(words[s:e+1])
        words[s:e+1] = [f'<{tag}>{merged_content}</{tag}>']
    new_text.append(' '.join(words))

df['text'] = new_text
print(df.text.to_list())

运行输出

['This is <IN>an</IN> example text that <TAR>I</TAR> use in order to get an answer', 'Discussion: We are <IN>examining</IN> the possibility <TAR>of this solution</TAR>']

如果仅需要保留第二行结果,直接取df.text.iloc[1]即可匹配你给出的期望输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:06:02