如何将用户输入的标签添加至Pandas DataFrame对应列?
解决Pandas逐行更新标签时覆盖全部行的问题
问题重现
你的数据集定义如下:
import pandas as pd data = {'type': ['train', 'train', 'train', 'pool', 'pool', 'pool', 'pool', 'pool'], 'index': [0,1,2,3,4,5,6,7], 'corpus': ['a','b','c', 'd', 'e', 'f', 'g', 'h'], 'labels': [[1,0,0], [0,1,0], [1,1,0], None , None , None , None , None]} data = pd.DataFrame(data)
你需要为type='pool'的行手动输入标签,但原循环代码会把所有行的labels替换为最后一次输入的内容:
for row, c in data.iterrows(): if c['type'] == 'pool': a = input(f"Please enter your labels for the below text: \n\n {c['corpus']}") data['labels'] = a
问题根源:data['labels'] = a是对整个labels列赋值,而非仅当前行,所以每次循环都会覆盖所有行的标签值。
修正方案
核心修改点
- 使用
data.loc[row, 'labels']精准定位当前行的labels字段,避免全列覆盖 - 将用户输入的字符串格式(如
"1,0,0")转换为整数列表,与原有标签格式统一
完整修正代码
import pandas as pd data = {'type': ['train', 'train', 'train', 'pool', 'pool', 'pool', 'pool', 'pool'], 'index': [0,1,2,3,4,5,6,7], 'corpus': ['a','b','c', 'd', 'e', 'f', 'g', 'h'], 'labels': [[1,0,0], [0,1,0], [1,1,0], None , None , None , None , None]} data = pd.DataFrame(data) # 遍历行并更新指定行的标签 for row, c in data.iterrows(): if c['type'] == 'pool': # 获取用户输入并转换为整数列表 input_str = input(f"Please enter your labels for the below text: \n\n {c['corpus']}") label_list = [int(num.strip()) for num in input_str.split(',')] # 仅更新当前行的labels字段 data.loc[row, 'labels'] = label_list # 查看结果 print(data)
验证结果
执行后会得到符合预期的输出:
type corpus labels 0 train a [1, 0, 0] 1 train b [0, 1, 0] 2 train c [1, 1, 0] 3 pool d [1, 1, 1] 4 pool e [0, 0, 1] 5 pool f [0, 1, 0] 6 pool g [0, 0, 1] 7 pool h [1, 0, 0]
内容的提问来源于stack exchange,提问作者ForeverLearner
相关产品推荐
相关产品推荐

