我有两个 CSV 文件,我想比较它们以找出相似之处。这里我使用余弦相似度。第一个文件包含 2000 行关于每个候选人的简历的 7 列:标题、位置、教育、证书、技能、语言和多年的经验。第二个文件包含 3 行,它们具有不同的职位描述,但与第一个文件具有相同的列。现在,我想根据所有 7 列找出拥有 3 个工作的所有候选人之间的相似性。编码要匹配同名的列,找出它们之间的相似性。然后,将其保存到 CSV 文件中,该文件包含 2000 行和 7 列,其中包含相似性分数。
下面的编码产生相似性分数,但不在同一行。例如,直到 2000 年的第 1 行包含 tntle 列之间的相似性得分,其余列为空。 2001 到 4001 行包含位置列之间的相似性得分,依此类推。我想将数据保存到一个 CSV 文件中,该文件只有 2000 行和 7 列,其中包含相似性分数,这意味着第一行包含第一个候选人简历的那 7 列的相似性分数。
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
# read the data from the CSV files
df1 = pd.read_csv('data_clean.csv')
df2 = pd.read_csv('job_desc_clean.csv')
# define the columns to compare
columns_to_compare = ['Title','Location', 'Education', 'Certifications', 'Skills', 'Languages', 'years_experiences']
# create an empty dataframe to store the results
df_sim = pd.DataFrame()
# calculate similarity for each column
for col in columns_to_compare:
# concatenate the text columns from the two dataframes
text1 = df1[col].values.astype('U')
text2 = df2[col].values.astype('U')
all_text = np.concatenate([text1, text2])
# create a bag-of-words representation of the text
vectorizer = CountVectorizer(binary=True, min_df=1)
X = vectorizer.fit_transform(text1)
Y = vectorizer.transform(text2)
# calculate cosine similarity between the bag-of-words representations
similarity_matrix = cosine_similarity(X, Y)
# add the similarity matrix to the results dataframe
df_temp = pd.DataFrame(similarity_matrix, columns=[f"{col}_file2_row_{i}" for i in range(similarity_matrix.shape[1])])
df_temp.index = [f"{col}_file1_row_{i}" for i in range(similarity_matrix.shape[0])]
df_sim = pd.concat([df_sim, df_temp], axis=1)
# save the results to a new CSV file
df_sim.to_csv('similarity_matrix.csv', index=False)