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

如何使用Python从单列行中移除指定词汇并移入另一列

Python实现移除指定词汇并转移到新列

需求说明

从表格的指定列(示例为col A)中移除词汇列表['apple','banana']中的内容,将移除的词汇存入新增的col removed word列,原列保留剩余文本。

实现方案(基于pandas)

处理表格数据用pandas最便捷,以下是完整代码示例:

import pandas as pd

# 1. 构造示例数据(如果是读取现有文件,用pd.read_csv/Excel替换这部分)
data = {'col A': ['apple is good', 'banana tastes sweet', 'I like orange', 'apple and banana both nice']}
df = pd.DataFrame(data)

# 2. 定义处理函数
def process_text(text, target_words):
    removed_words = []
    remaining_text = text
    # 遍历目标词汇,检查并移除
    for word in target_words:
        if word in remaining_text:
            removed_words.append(word)
            # 移除词汇,同时清理多余空格
            remaining_text = remaining_text.replace(word, '').strip()
            remaining_text = ' '.join(remaining_text.split())
    # 返回剩余文本和移除的词汇(多词汇用逗号分隔)
    return remaining_text, ', '.join(removed_words)

# 3. 应用函数到数据框
target_words = ['apple', 'banana']
df[['col A', 'col removed word']] = df['col A'].apply(
    lambda x: pd.Series(process_text(x, target_words))
)

# 4. 查看结果
print(df)

代码说明

  • 处理函数process_text会遍历目标词汇,检查当前文本是否包含该词,若包含则记录并移除,同时清理因移除产生的多余空格
  • 一行中包含多个目标词汇时,会把所有移除的词用逗号分隔存入新列
  • 原列不包含任何目标词汇时,新列显示为空字符串

运行结果

col A col removed word
0           is good             apple
1      tastes sweet            banana
2    I like orange                  
3  and both nice      apple, banana

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:39:22