【问题标题】:Find number of keyword matches in pandas column that is in a list在列表中的 pandas 列中查找关键字匹配的数量
【发布时间】:2018-09-17 20:29:29
【问题描述】:

我有一个如下所示的 pandas 数据框:

Type        Keywords 
----        --------
Animal      [Pigeon, Bird, Raccoon, Dog, Cat]
Pet         [Dog, Cat, Hamster]
Pest        [Rat, Mouse, Raccoon, Pigeon]
Farm        [Chicken, Horse, Cow, Sheep]
Predator    [Wolf, Fox, Raccoon]

假设我有以下字符串:

input = "There is a dead rat and raccoon in my pool"

鉴于我对字符串进行标记并删除停用词,使其变为

input = [Dead, Rat, Raccoon, Pool]

我需要遍历每一行并找到关键字匹配次数最多的行。对于给定的示例,结果将如下所示:

Type        Keywords                            Matches
----        --------                            -------
Animal      [Pigeon, Bird, Raccoon, Dog, Cat]   1
Pet         [Dog, Cat, Hamster]                 0
Pest        [Rat, Mouse, Raccoon, Pigeon]       2
Farm        [Chicken, Horse, Cow, Sheep]        0
Predator    [Wolf, Fox, Raccoon]                1

输出将是匹配次数最多的前三个类型名称。

在上述情况下,由于“害虫”类别的匹配数最多,因此将被选为最高匹配。此外,将选择动物和捕食者类别。因此,按顺序输出将是:

output = [Pest, Animal, Predator]

使用嵌套的 for 循环执行此任务很容易,但由于我有数千个此类行,因此我正在寻找更好的解决方案。 (另外由于某些原因,我在 pandas 中使用非内置函数时遇到了很多错误,可能是因为矢量化?)

我查看了 pandas 内置的 groupby 和 isin 函数,但据我所知,它们无法让我得到我想要的输出(如果我不正确,我一点也不感到惊讶在这个假设中)。

接下来我研究了 pandas 对集合和哈希图的使用,但不幸的是,我的编码知识和目前的能力还不够熟练,无法制定可靠的解决方案。 This StackOverflow link 尤其让我更接近我想要的,尽管它没有找到前三个匹配的行名。

如果有任何帮助或建议,我将不胜感激。

【问题讨论】:

  • 一个简单的方法是使用 apply 并设置交集计数

标签: python python-3.x pandas nlp nltk


【解决方案1】:

您可以查看isin

df['Matches']=pd.DataFrame(df.Keywords.values.tolist()).isin(s).sum(1)


df.loc[df['Matches']>0,'Type'].values.tolist()

【讨论】:

    【解决方案2】:

    在DataFrame中存储和操作列表效率不是很高,话虽如此,我们可以在这里使用集合交集:

    设置

    s = set(['Dead', 'Rat', 'Raccoon', 'Pool'])
    

    现在使用列表解析(比apply 更快):

    out = df.assign(Matches=[len(set(el) & s) for el in df.Keywords])
    
    <!- ->
    
           Type                           Keywords  Matches
    0    Animal  [Pigeon, Bird, Raccoon, Dog, Cat]        1
    1       Pet                [Dog, Cat, Hamster]        0
    2      Pest      [Rat, Mouse, Raccoon, Pigeon]        2
    3      Farm       [Chicken, Horse, Cow, Sheep]        0
    4  Predator               [Wolf, Fox, Raccoon]        1
    

    查找匹配最多的三行:

    out.loc[out.Matches.nlargest(3).index].Type.tolist()
    

    ['Pest', 'Animal', 'Predator']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 2019-01-05
      • 2017-12-31
      • 2020-05-18
      • 2018-02-26
      • 2022-11-18
      • 2022-06-12
      相关资源
      最近更新 更多