Python搜索列表中单词的数据帧,并跟踪找到的单词和频率

2024-09-24 04:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经引用了下面的帖子,它非常有用,但我还需要更进一步。 Python - Searching a string within a dataframe from a list

我不仅要在我的数据框中搜索单词列表,还要跟踪是否找到多个单词以及频率。因此,使用上述帖子中的示例:

如果这是我的搜索列表

search_list = ['STEEL','IRON','GOLD','SILVER']

这是我正在搜索的数据框

      a    b             
0    123   'Blah Blah Steel'
1    456   'Blah Blah Blah Steel Gold'
2    789   'Blah Blah Gold'
3    790   'Blah Blah blah'

我希望我的输出是

      a    b                        c               d
0    123   'Blah Blah Steel'      'STEEL'           1
1    789   'Blah Blah Steel Gold' 'STEEL','GOLD'    2
2    789   'Blah Blah Gold'       'GOLD'            1
3    790   'Blah Blah blah'

我如何在上面提到的文章中扩展这些令人敬畏的解决方案,以获得所需的输出?目前,我正在利用投票结果最高的答案作为起点

我更关心的是能够标记列表中的多个单词。我还没有找到任何方法来做到这一点。如果在这一步中无法实现,我可以将字符串计数函数应用于数据帧以创建频率列。如果有一种方法可以一步完成这一切,那也很高兴知道

提前谢谢


Tags: 数据方法列表stringsearching单词帖子list
2条回答

您可以使用re.findall()而不是extract()来执行所需的操作

import re

search_list = ['STEEL','IRON','GOLD','SILVER']

df['c'] = df.b.str.findall('({0})'.format('|'.join(search_list)), flags=re.IGNORECASE)
df['d'] = df['c'].str.len()

此输出如下所示:

enter image description here

#turn column b into a list of uppercases
  df.b=df.b.str.upper().str.split('\s')

#Because you have two lists, use the apply function to turn them into sets
#..and leverage the rich membership functions encased in sets.
# Using intersection, you will find items in each list. 
#Then use list.str.len() to count.

df=df.assign(c=df.b.apply(lambda x:[*{*x}&{*search_list}])\
.str.join(','),d=df.b.apply(lambda \
x:[*{*x}&{*search_list}]).str.len())



                       b           c      d
0        [BLAH, BLAH, STEEL]       STEEL  1
1  [BLAH, BLAH, STEEL, GOLD]  GOLD,STEEL  2
2         [BLAH, BLAH, GOLD]        GOLD  1
3         [BLAH, BLAH, BLAH]              0

相关问题 更多 >