检查 column1 是否包含 list 中的任何值

72 阅读1分钟

你可以使用 str.contains| (或运算符) 来检查 column1 是否包含 list 中的任何值,并创建一个新列进行标记。


✅ 方法 1:使用 str.contains

import pandas as pd

# 示例 DataFrame
data = {"column1": ["Apple", "Banana", "Cherry", "Date", "Egg", "Grape", "AB"]}
df = pd.DataFrame(data)

# 关键词列表
keywords = ["A", "B", "C", "D", "E"]

# 使用正则表达式查找匹配项
df["match_flag"] = df["column1"].str.contains("|".join(keywords), regex=True).astype(int)

print(df)

📌 代码解析

  1. "|".join(keywords)

    • list 转换为 "A|B|C|D|E" 这样的正则表达式模式。
    • | 代表 "或" ,匹配任意一个字符即为 True。
  2. df["column1"].str.contains(..., regex=True)

    • 检查 column1 是否包含 list 中的值
    • regex=True 启用正则匹配。
  3. .astype(int)

    • True/False 转换为 1/0,方便标记。

📌 示例输出

column1match_flag
Apple1
Banana1
Cherry1
Date1
Egg1
Grape0
AB1

这样你就可以对 df 中的 column1 进行标记,判断是否包含 list 中的任意值! 🚀