Car*_*Cox 5 python nlp boolean dataframe pandas
循环搜索要搜索的二元组列表,我需要根据每个二元组是否存在于标记化的 pandas 系列中为每个二元组创建一个布尔字段。如果您认为这是一个好问题,我将不胜感激!
二元组列表:
bigrams = ['data science', 'computer science', 'bachelors degree']
Run Code Online (Sandbox Code Playgroud)
数据框:
df = pd.DataFrame(data={'job_description': [['data', 'science', 'degree', 'expert'],
['computer', 'science', 'degree', 'masters'],
['bachelors', 'degree', 'computer', 'vision'],
['data', 'processing', 'science']]})
Run Code Online (Sandbox Code Playgroud)
期望的输出:
job_description data science computer science bachelors degree
0 [data, science, degree, expert] True False False
1 [computer, science, degree, masters] False True False
2 [bachelors, degree, computer, vision] False False True
3 [data, bachelors, science] False False False
Run Code Online (Sandbox Code Playgroud)
标准:
我尝试过的:
失败的: df = [x for x in df['job_description'] if x in bigrams]
失败的:df[bigrams] = [[any(w==term for w in lst) for term in bigrams] for lst in df['job_description']]
失败:无法适应此处的方法 ->将三元组、二元组和一元组与文本匹配;如果一元或二元是已经匹配的三元的子串,则通过;Python
失败:无法让这个适应,或者 ->比较两个二元组列表并返回匹配的二元组
失败:此方法非常接近,但无法使其适应二元组 ->根据标记化的 pandas 数据框中出现的特定术语创建新的布尔字段
感谢您的任何帮助,您可以提供!
您也可以尝试使用numpy
and nltk
,这应该相当快:
import pandas as pd
import numpy as np
import nltk
bigrams = ['data science', 'computer science', 'bachelors degree']
df = pd.DataFrame(data={'job_description': [['data', 'science', 'degree', 'expert'],
['computer', 'science', 'degree', 'masters'],
['bachelors', 'degree', 'computer', 'vision'],
['data', 'processing', 'science']]})
def find_bigrams(data):
output = np.zeros((data.shape[0], len(bigrams)), dtype=bool)
for i, d in enumerate(data):
possible_bigrams = [' '.join(x) for x in list(nltk.bigrams(d)) + list(nltk.bigrams(d[::-1]))]
indices = np.where(np.isin(bigrams, list(set(bigrams).intersection(set(possible_bigrams)))))
output[i, indices] = True
return list(output.T)
output = find_bigrams(df['job_description'].to_numpy())
df = df.assign(**dict(zip(bigrams, output)))
Run Code Online (Sandbox Code Playgroud)
| | job_description | data science | computer science | bachelors degree |
|---:|:----------------------------------------------|:---------------|:-------------------|:-------------------|
| 0 | ['data', 'science', 'degree', 'expert'] | True | False | False |
| 1 | ['computer', 'science', 'degree', 'masters'] | False | True | False |
| 2 | ['bachelors', 'degree', 'computer', 'vision'] | False | False | True |
| 3 | ['data', 'processing', 'science'] | False | False | False |
Run Code Online (Sandbox Code Playgroud)