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

当Pandas中Keyword列值重复时,如何覆盖相邻Group列值?

Pandas修改指定Keyword对应的Group列值

针对你需要的需求——当Keyword列出现特定字符串(比如commercial office cleaning services)时,将对应的Group列值替换为指定内容,用Pandas可以通过布尔索引定位目标行来实现,直观易懂,适合新手快速上手。

具体实现步骤

  • 定位目标行:通过df['Keyword'] == '目标字符串'生成布尔筛选条件,精准找出符合要求的行
  • 赋值修改:直接对筛选出的行的Group列,赋值为你指定的内容

完整示例代码

import pandas as pd

data = [
    ["commercial cleaning services", "commercial cleaning services"],
    ["commercial office cleaning services", "commercial cleaning services"],
    ["janitorial cleaning services", "commercial cleaning services"],
    ["commercial office services", "commercial cleaning"],
    # 新增一行重复的目标Keyword,测试重复场景的修改效果
    ["commercial office cleaning services", "旧分组内容"]
]
df = pd.DataFrame(data, columns=["Keyword", "Group"])

# 输出修改前的数据
print("修改前:")
print(df)

# 核心修改代码
target_keyword = "commercial office cleaning services"
new_group_content = "commercial cleaning services"
df.loc[df['Keyword'] == target_keyword, 'Group'] = new_group_content

# 输出修改后的数据
print("\n修改后:")
print(df)

代码说明

  • df.loc[筛选条件, 列名]:Pandas中定位特定行和列的常用方法,能精准选中你需要修改的范围
  • df['Keyword'] == target_keyword:逐行判断Keyword是否匹配目标字符串,返回一组True/False值,loc会自动选中所有标记为True的行
  • 不管目标Keyword重复出现多少次,只要匹配上就会被统一修改为指定的Group值

如果需要同时处理多个Keyword的替换需求,可以用字典映射批量操作:

# 多关键词批量替换示例
keyword_to_group = {
    "commercial office cleaning services": "commercial cleaning services",
    "janitorial cleaning services": "janitorial services"
}

# 遍历字典完成批量修改
for keyword, group in keyword_to_group.items():
    df.loc[df['Keyword'] == keyword, 'Group'] = group

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:05:31