[英]find total occurences of a list of words in a given column (SQL/Pandas DataFrame)
我有一个关于某个平台用户信息的 SQL 数据库。 数据库有两列:用户名、描述
我还有一个单词/表达式列表(总共大约 200 个单词),我想检查它们是否存在于每个用户的描述中:
单词 = ['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 默认函数也会有帮助。
最终结果应该是这样的:
用户名 | 描述 | 全部的 |
---|---|---|
哈哈 | Python书呆子,游泳 | 1 |
vnjfnn | 保守派,HTML 开发人员 | 1 |
af5a45 | 不适用 | 0 |
阿夫贾 | 喜欢使用 CSS 和 HTML | 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
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
切换
另外,如果单词在user.description
中大量重复,请考虑使用Set
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.