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

pandas循环追加用户标注数据到DataFrame时文本重复行问题

问题根因

你遇到的行重复问题来自三个逻辑错误:

  1. 构造DataFrame入参时,corpus传入单个字符串,标签字段传入列表,pandas会自动按列表长度做广播,生成和标签数量一致的多行,每行重复填充同一个文本,单个标签占一行
  2. 代码中question.lower()没有将转换结果赋值回原变量,用户输入大写Y/N时会出现匹配失效的问题
  3. 每次循环都会覆盖df_new_labels变量,最终只会保留最后一次标注的内容,无法收集所有文本的标注结果
修正逻辑
  • 提前初始化空列表存储所有标注条目,循环过程中只做单条结果的收集,循环结束后一次性生成DataFrame
  • 单条文本对应的有效标签列表,用字符串拼接方法转成逗号分隔的单值,不要直接传入列表,避免pandas自动拆行
  • 修复大小写转换的赋值问题,可选增加输入内容的空格清洗,避免误输入空格产生无效标签
修正后代码
import pandas as pd

count = 0
annotation_result = []

for i in sorted_dict:
    count += 1
    text_content = pool_df['corpus'][i]
    print(f'\n\nText {count}: index {i} \n\n{text_content}')

    confirm = input('Enter new label(s) for this text? type Y for yes or N for no: ')
    confirm = confirm.lower()
    if confirm == 'n':
        print('see you later')
        break
    elif confirm == 'y':
        print('\n\nIf you think that the label printed is associated with the corpus, type the label otherwise hit "space"\n\n')
        label_x = input('x: ').strip()
        label_y = input('y: ').strip()
        label_z = input('z: ').strip()
        label_a = input('a: ').strip()
        label_b = input('b: ').strip()
        label_c = input('c: ').strip()
        label_d = input('d: ').strip()
        
        all_labels = [label_x, label_y, label_z, label_a, label_b, label_c, label_d]
        valid_labels = [label for label in all_labels if label != '']
        print(f'The new labels are: {valid_labels}')
        
        # 单条标注结果追加到总列表,标签用逗号拼接为字符串
        annotation_result.append({
            'corpus': text_content,
            'labels': ', '.join(valid_labels) # 要无空格分隔就改成','.join(valid_labels)
        })

# 生成最终新标注的DataFrame
df_new_labels = pd.DataFrame(annotation_result)
# 后续追加到已有DataFrame可直接使用:
# total_df = pd.concat([your_existing_df, df_new_labels], ignore_index=True)
效果说明

运行后生成的DataFrame会完全匹配你的预期格式:单条文本占一行,对应所有标签存在同一行的labels字段中,不会出现文本重复、标签单独占行的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:27:23