时间:2022-02-13 10:49:01 | 栏目:Python代码 | 点击:次
此方法是两个表构建某一相同字段,然后全连接,在做匹配结果筛选,此方法针对数据量不大的时候,逻辑比较简单,但是内存消耗较大
import pandas as pd import numpy as np import re
#关键词数据 df_keyword = pd.DataFrame({ "keyid" : np.arange(5), "keyword" : ["numpy", "pandas", "matplotlib", "sklearn", "tensorflow"] }) df_keyword
df_sentence = pd.DataFrame({ "senid" : np.arange(10,17), "sentence" : [ "怎样用pandas实现merge?", "Python之Numpy详细教程", "怎么使用Pandas批量拆分与合并Excel文件?", "怎样使用pandas的map和apply函数?", "深度学习之tensorflow简介", "tensorflow和numpy的关系", "基于sklearn的一些机器学习的代码" ] }) df_sentence
df_keyword['match'] = 1 df_sentence['match'] = 1
df_merge = pd.merge(df_keyword, df_sentence) df_merge
def match_func(row): return re.search(row["keyword"], row["sentence"], re.IGNORECASE) is not None df_merge[df_merge.apply(match_func, axis = 1)]
匹配结果如下
此方法对编程能力有要求,在大数据集上计算量较方法一小很多
key_word_dict = { row.keyword : row.keyid for row in df_keyword.itertuples() } key_word_dict
{'numpy': 0, 'pandas': 1, 'matplotlib': 2, 'sklearn': 3, 'tensorflow': 4}
def merge_func(row): #新增一列,表示可以匹配的keyid row["keyids"] = [ keyid for key_word, keyid in key_word_dict.items() if re.search(key_word, row["sentence"], re.IGNORECASE) ] return row df_merge = df_sentence.apply(merge_func, axis = 1)
df_merge
df_result = pd.merge( left = df_merge.explode("keyids"), right = df_keyword, left_on = "keyids", right_on = "keyid") df_result