【问题标题】:Creating a new column by finding exact word in a column of strings通过在字符串列中查找确切的单词来创建新列
【发布时间】:2018-09-21 00:31:48
【问题描述】:

如果列表中的任何单词与数据框字符串列完全匹配,我想创建一个包含 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),则 data["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

【问题讨论】:

  • @Georgy list_provided 有很多词。此外,如果我使用 str.contains(),即使第二行也会被标记为 1 如果我使用 data["text"].isin(list_provided) 它会使所有三行都为零,因为它只查找只有这些单词的单元格

标签: python string python-3.x pandas dataframe


【解决方案1】:

您可以通过 pd.Series.applysum 使用生成器表达式来做到这一点:

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

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

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

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

【讨论】:

  • 对于我在列表中的单词有空格的情况,如何解决?我已经用编辑更新了我的帖子(编辑 2)
  • 要复杂得多。我建议你问一个单独的问题。我将在这里回滚您之前的问题。
  • 当然...我会这样做的
【解决方案2】:

编辑 1

试试这个代码

import pandas as pd
dataframe = [["simultaneous there the","simultaneous there","mul why","mul"],["a","b","c","d"]]
list_of_word = ["mul","the"]


dic = {
    "id": dataframe[1],
    "text": dataframe[0] 
}

DataF = pd.DataFrame(dic)

found = []
for key in DataF["text"]:
    anyvari = False
    for damn in key.split(" "):

        if(damn==list_of_word[0] or damn==list_of_word[1]):
            anyvari = True

            break
        else:
            continue
    if(anyvari!=True):
        found.append(0)
    else:
        found.append(1)


DataF["found"] = found         


print(DataF)

它会给你这样的

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

【讨论】:

  • 谢谢@Amam。如果我在列表中的话有空格。例如,我在列表中的单词是“mul the”。那么如何解决这个问题呢?那我就不能使用 key.split 了!!
  • 你的意思是,如果单词是“mul the”,那么它找到了 2?或者什么,
猜你喜欢
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
相关资源
最近更新 更多