gpt4 book ai didi

python - 通过在一列字符串中找到确切的单词来创建一个新列

转载 作者:太空宇宙 更新时间:2023-11-03 14:00:26 25 4
gpt4 key购买 nike

如果列表中的任何单词与数据框字符串列完全匹配,我想创建一个包含 1 或 0 的新列。

list_provided=["mul","the"]
#how my dataframe looks
id text
a simultaneous there the
b simultaneous there
c mul why

预期输出

id  text                     found
a simultaneous there the 1
b simultaneous there 0
c mul why 1

第二行赋值为 0,因为 “mul”或“the”在字符串列“text”中不完全匹配

代码尝试到现在

#For exact match I am using the below code
data["Found"]=np.where(data["text"].str.contains(r'(?:\s|^)penalidades(?:\s|$)'),1,0)

如何遍历循环以找到所提供单词列表中所有单词的精确匹配?

编辑:如果我按照 Georgey 的建议使用 str.contains(pattern),则数据 ["Found"] 的所有行都变为 1

data=pd.DataFrame({"id":("a","b","c","d"), "text":("simultaneous there the","simultaneous there","mul why","mul")})
list_of_word=["mul","the"]
pattern = '|'.join(list_of_word)
data["Found"]=np.where(data["text"].str.contains(pattern),1,0)

Output:
id text found
a simultaneous there the 1
b simultaneous there 1
c mul why 1
d mul 1

找到的列第二行这里应该是0

最佳答案

您可以使用 pd.Series.apply 和带有生成器表达式的 sum 来做到这一点:

import pandas as pd

df = pd.DataFrame({'id': ['a', 'b', 'c'],
'text': ['simultaneous there the', 'simultaneous there', 'mul why']})

test_set = {'mul', 'the'}

df['found'] = df['text'].apply(lambda x: sum(i in test_set for i in x.split()))

# id text found
# 0 a simultaneous there the 1
# 1 b simultaneous there 0
# 2 c mul why 1

上面提供了一个计数。如果您只需要 bool 值,请使用 any:

df['found'] = df['text'].apply(lambda x: any(i in test_set for i in x.split()))

对于整数表示,链.astype(int)

关于python - 通过在一列字符串中找到确切的单词来创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49769706/

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