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

Pandas合并字符串列去重时多词值处理及去重不彻底问题如何解决

问题解决方法

你原代码的核心问题是没有对单元格内用逗号分隔的多个水果值做拆分,直接将整个单元格的完整字符串作为去重单位,自然无法处理内部多值、带空格的水果名这类场景,也没法正确去重跨单元格的重复水果。

正确的实现代码如下:

import pandas as pd
import numpy as np

data = {'fruit1':["organge, apple", "apple", "organge, dragon fruit", "organge, others", "others"],
        'fruit2':["apple, organge", "others", "dragon fruit, organge", "watermelon", "others"]}
df = pd.DataFrame(data)

def merge_fruits(row):
    # 收集两个列的所有水果,过滤掉others
    fruit_list = []
    for col in ['fruit1', 'fruit2']:
        if row[col] == 'others':
            continue
        # 按逗号+空格拆分单个水果条目,自动适配多单词水果名
        fruits = row[col].split(', ')
        fruit_list.extend(fruits)
    # 去重且保留水果出现的顺序,Python3.7+原生支持
    unique_fruits = list(dict.fromkeys(fruit_list))
    # 空值替换为others
    return ', '.join(unique_fruits) if unique_fruits else 'others'

df["together"] = df.apply(merge_fruits, axis=1)

运行后输出完全匹配预期:

fruit1fruit2together
organge, appleapple, organgeapple, organge
appleothersapple
organge, dragon fruitdragon fruit, organgeorgange, dragon fruit
organge, otherswatermelonorgange, watermelon
othersothersothers

如果不需要保留水果出现的顺序,也可以将去重逻辑替换为unique_fruits = list(set(fruit_list)),执行效率更高。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:18:03