【问题标题】:find total occurences of a list of words in a given column (SQL/Pandas DataFrame)查找给定列中单词列表的总出现次数(SQL/Pandas DataFrame)
【发布时间】:2021-12-15 02:26:52
【问题描述】:

我有一个关于某个平台的用户信息的 SQL 数据库。 数据库有两列:用户名、描述

我还有一个单词/表达式列表(总共大约 200 个单词),我想检查它们是否存在于每个用户的描述中:

words = ['python', 'css', 'html', ...]

我想做的是创建一个新列 - 例如名为“total” - 然后计算列表中每个用户描述中使用的单词/表达式的总数。

换句话说,这就是我想要使用嵌套的 for 循环:

for user in users:
    for word in words:
        if word in user.description:
            user.total += 1

但是,我的数据量很大(5+ 百万用户),我想知道是否有更有效的方法来实现这一目标。我更喜欢用 SQL 来做,不过 Python Pandas 的默认函数也会有帮助。

最终结果应该是这样的:

username description total
afhkjh Python Nerd, Swimming 1
vnjfnn Conservative, HTML Developer 1
af5a45 NA 0
afkjah Love working with CSS and HTML 2

【问题讨论】:

    标签: python sql pandas


    【解决方案1】:
    count = []
    for user in users:
        count.append(sum(word in user.description for word in words))
    df["Total"] = Count
    

    可能有更好的方法。下面的代码块花了 3.6 秒为我运行

    words = ["quick","lazy"]
    temp = []
    for i in range(5000000):
        temp.append(sum(word in "The quick brown fox jumps over the lazy dog" for word in words))
    

    如果user.description 比使用user.description.split(" ") 的单词列表短,您可以尝试反过来切换

    此外,如果user.description 中的单词重复次数过多,请考虑使用Set

    【讨论】:

      【解决方案2】:

      数据:

      >>> import pandas as pd
      >>> words = ['python', 'css', 'html']
      >>> df = pd.DataFrame({'username': {0: 'afhkjh', 1: 'vnjfnn', 2: 'af5a45', 3: 'afkjah'},
       'description': {0: 'Python Nerd, Swimming',
        1: 'Conservative, HTML Developer',
        2: 'NA',
        3: 'Love working with CSS and HTML'}})
      >>> df
      
          username    description
      0   afhkjh      Python Nerd, Swimming
      1   vnjfnn      Conservative, HTML Developer
      2   af5a45      NA
      3   afkjah      Love working with CSS and HTML
      
      >>> df['total'] = df.description.str.lower().apply(str.split).apply(lambda x:len(set(words) & set(x)))
      >>> df
      
          username    description                     total
      0   afhkjh      Python Nerd, Swimming           1
      1   vnjfnn      Conservative, HTML Developer    1
      2   af5a45      NA                              0
      3   afkjah      Love working with CSS and HTML  2
      
      
      

      【讨论】:

      • 非常感谢,这非常适合单个单词!但是,在我的列表中,也有许多表达式包含多个单词,例如“R Programming”或“Object Oriented Programming”之类的。这样的表达怎么也算?这就是为什么我最初想检查 like (if expression in description) 以便不管表达式的长度如何都可以检查。
      • @MahsaZ 做了类似的事情:df['total'] = df['description'].str.extractall('(?i)({})'.format('|'.join(words))).groupby(level=0).size() 让你靠近?
      • 不幸的是,这行代码为所有行找到了描述中实际存在的更多单词/表达式。为一行找到的最少字数为 17,最多约 70 个。
      猜你喜欢
      • 2023-04-09
      • 2018-01-14
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多