gpt4 book ai didi

python - 在列中搜索单词列表,如果找到单词则创建一个 boolean 列

转载 作者:行者123 更新时间:2023-12-01 00:34:43 26 4
gpt4 key购买 nike

您好,问题是通过搜索单词列表来循环遍历列,然后如果找到搜索到的任何列表单词,则创建一个 boolean 列。这是我的代码

# Code naf related to sport.
code = ["3230Z","4764Z","7721Z","8551Z","9311Z", "9312Z", "9313Z", "9319Z",
"9329Z", "364Z" "524W", "714B", "804C", "926A", "926C", "930L", "927C",
"923K"]

# check keywords of code into "Code_Naf" column
for branch in code:
df_codeNaf["topNAF"] = df_codeNaf["Code_NAF"].str.contains("3230Z" or "4764Z" or "7721Z" or "8551Z"
or "9311Z" or "9312Z" or "9313Z" or "9319Z"
or "9329Z" or "364Z" "524W" or "714B" or
"804C" or "926A" or "926C" or "930L" or
"927C" or "923K")

当我查看 topNaf 列时,我发现只有 2 个 True,但实际上有两个以上。我的代码有什么问题吗?谢谢

最佳答案

您的问题是您对code中的每个banch更改了df_codeNaf['topNAF']。您的代码可以通过以下方式修复:

df_codeNaf['topNAF'] = False
for branch in code:
df_codeNaf['topNAF'] = df_codeNaf['topNAF'] | df_codeNaf['Code_NAF'].str.contains(branch).

但更好的是,您可以在一行中尝试使用 regexcontains :

pattern = '|'.join(code)
df_codeNaf['topNAF'] = df_codeNaf['Code_NAF'].str.contains(pattern)

关于python - 在列中搜索单词列表,如果找到单词则创建一个 boolean 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57890764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com