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

如何统一修改Pandas中text值相同但label不同的行标签

统一Pandas DataFrame中重复文本的冲突标签:将fruit改为veg

需求:修改Pandas DataFrame中text值相同但label不同的行标签,将其中label为fruit的统一改为veg。

示例输入

输入代码

import pandas as pd

df = pd.DataFrame({"text": ["bannana", "tomato", "potato", "potato", "lemon", "cucamber"],
                   "label": ["fruit", "veg", "fruit", "veg", "fruit", "veg"], 
                    })
                    
print(df)

输入输出

text   label
0  bannana  fruit
1   tomato    veg
2   potato  fruit
3   potato    veg
4    lemon  fruit
5 cucamber    veg

可以看到,potato对应的标签同时存在fruit和veg,属于需要修正的冲突文本。

解决代码

import pandas as pd

df = pd.DataFrame({"text": ["bannana", "tomato", "potato", "potato", "lemon", "cucamber"],
                   "label": ["fruit", "veg", "fruit", "veg", "fruit", "veg"], 
                    })

# 筛选出存在多种标签的text值
conflicting_texts = df.groupby('text')['label'].nunique()[lambda x: x > 1].index

# 对冲突文本中label为fruit的行替换为veg
df.loc[(df['text'].isin(conflicting_texts)) & (df['label'] == 'fruit'), 'label'] = 'veg'

print(df)

最终输出

text   label
0  bannana  fruit
1   tomato    veg
2   potato    veg
3   potato    veg
4    lemon  fruit
5 cucamber    veg

代码说明

  • df.groupby('text')['label'].nunique():按text分组,统计每个文本对应的不同标签数量
  • 后续筛选逻辑:提取出标签数量大于1的文本,得到所有存在冲突的text集合
  • df.loc[条件, 'label'] = 'veg':精准定位到冲突文本且标签为fruit的行,批量修改标签为veg

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:35:29