Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 熊猫:在列表中循环并从列中的列表中查找单词。。。使用从列表中找到的单词创建新列_String_List_Pandas_Find_Conditional - Fatal编程技术网

String 熊猫:在列表中循环并从列中的列表中查找单词。。。使用从列表中找到的单词创建新列

String 熊猫:在列表中循环并从列中的列表中查找单词。。。使用从列表中找到的单词创建新列,string,list,pandas,find,conditional,String,List,Pandas,Find,Conditional,我的清单如下: 列表=[“狗”、“猫”、“马”、“鸟”] 下面是一个示例数据框。我想让我的代码说:如果文本在列表中包含一个单词,那么创建一个名为EXTRACT的新列,该列将挑选出关键字并将它们放在新列中 ID TEXT 1 hello you person 2 you have a dog 3 the bird flew 4 the horse is here 5 bird bird bird 下面

我的清单如下:

列表=[“狗”、“猫”、“马”、“鸟”]

下面是一个示例数据框。我想让我的代码说:如果文本在列表中包含一个单词,那么创建一个名为EXTRACT的新列,该列将挑选出关键字并将它们放在新列中

ID  TEXT               
1   hello you person    
2   you have a dog     
3   the bird flew      
4   the horse is here  
5   bird bird bird     
下面是我想要的数据帧:

ID  TEXT               EXTRACT
1   hello you person    
2   you have a dog     dog
3   the bird flew      bird
4   the horse is here  horse
5   bird bird bird     bird

我知道一种使用语法的非有效方法,例如:如果单词出现在文本列中,则将该单词放入新列中。但是我的真实数据框架有一长串单词,上面的方法太单调乏味了

您可以尝试使用df.apply并设置交叉点,以查看哪些单词同时出现在文本列和单词列表中

当文本列

中出现不止一个单词时,您需要考虑应该发生什么。
def word_finder(x):
  df_words = set(x.split(' '))
  extract_words =  word_set.intersection(df_words)
  return ', '.join(extract_words)

df = pd.DataFrame(data = {'text' : ['hello you person', 'you have a dog', 'the bird flew', 'the horse is here', 'bird bird bird', 'dog and cat']})

word_set = {'dog', 'cat', 'horse', 'bird'}

df['extract'] = df.text.apply(word_finder)
输出

                text   extract
0   hello you person          
1     you have a dog       dog
2      the bird flew      bird
3  the horse is here     horse
4     bird bird bird      bird
5        dog and cat  dog, cat