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

Pandas如何检查DataFrame当前列值是否存在于前面列并按规则替换

首先导入pandas并构造原始数据:

import pandas as pd

d = {'Person1': ['Apple', 'Mango'], 'Person2': ['Orange', 'Apple'],  'Person3': ['Orange', 'Apple'], 'Person4': ['Orange', 'Apple'], 'Person5': ['Watermelon', 'Mango']}
df1 = pd.DataFrame(data=d)

使用逐行遍历判断的逻辑处理即可,核心是维护每行已出现的值的集合:

def handle_row(row):
    existed = set()
    res = []
    for val in row:
        if val in existed:
            res.append(True)
        else:
            res.append(val)
            existed.add(val)
    return pd.Series(res, index=row.index)

df_res = df1.apply(handle_row, axis=1)

执行print(df_res)即可得到你需要的输出:

Person1 Person2 Person3 Person4     Person5
0   Apple  Orange    True    True  Watermelon
1   Mango   Apple    True    True        True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:24:04