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

对比DataFrame列值并更新:为匹配项添加等号后缀

处理DataFrame name列的等号匹配替换问题

首先重现你的数据:

import pandas as pd

a = [{'name': 'AAA'}, {'name': 'BBB'}, {'name': 'BBB'}, {'name': 'CCC'}, {'name': 'DDD'}, {'name': 'EEE'}]
df = pd.DataFrame(a)
b = [{'name': 'AAA='}, {'name': 'BBB='}, {'name': 'DDD='}]
df1 = pd.DataFrame(b)

要实现仅当df的name值在df1中存在对应带等号的版本时,给df的name添加等号,可以按以下步骤操作:

  1. 提取df1中去掉末尾等号的名称集合,用于快速匹配:
target_names = set(df1['name'].str.rstrip('='))
  1. 用条件替换修改df的name列:
import numpy as np

df['name'] = np.where(df['name'].isin(target_names), df['name'] + '=', df['name'])

运行后输出的df结果为:

name
0  AAA=
1  BBB=
2  BBB=
3   CCC
4  DDD=
5   EEE

代码解释

  • str.rstrip('='):移除df1中name列每个值末尾的等号,得到不带等号的基准名称
  • 转成集合set():集合的成员查询效率远高于列表,适合处理大数据量
  • np.where():批量进行条件判断,比逐行遍历的apply更高效,满足条件的名称添加等号,不满足的保留原内容

如果偏好更直观的逐行处理方式,也可以用apply:

df['name'] = df['name'].apply(lambda x: x + '=' if x in target_names else x)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:35:17