我有一个包含工作职业作为主要变量的数据框架,对于每个职业来说,这是一组组成一份工作的技能。我试图用余弦作为距离度量来寻找工件之间的余弦相似性。到目前为止,我设法得到了余弦矩阵/数组,但是我不能把这个数组作为包含职业之间相似性的数据框架。请参见下面的数据集示例、我迄今使用的代码以及我希望得到的预期结果。
数据集
INDEX 3D studio Accountancy Cooking
3d modeling 1 0 0
IC auditor 0 1 0
Chef 0 1 0应用余弦相似
import numpy as np
from sklearn.metrics import pairwise_distances
from scipy.spatial.distance import cosine
dist_out = 1-pairwise_distances(data_k_T, metric="cosine")结果以数组的形式出现。
0 1 2 3
1 1 0 0
2 0 1 0.65
3 0 0.65 1如何把这个变成成对的比较格式,我试着使用连接和整形,但我失败了。
理想的结果是:
Occ_s Occ_T Score
3d modeling 3d modeling 1
3d modeling IC auditor 0
3d modeling Chef 0.65注意-矩阵很大,这个余弦分数是虚构的。
发布于 2018-08-06 08:13:34
我认为需要具有指定列和索引的DataFrame构造函数,然后通过stack进行整形。
dist_out = 1-pairwise_distances(data_k_T, metric="cosine")
print (dist_out)
[[1. 0. 0.]
[0. 1. 1.]
[0. 1. 1.]]
df = pd.DataFrame(dist_out, index=data_k_T.index, columns=data_k_T.columns)
print (df)
3Dstudio Accountancy Cooking
3d modeling 1.0 0.0 0.0
IC auditor 0.0 1.0 1.0
Chef 0.0 1.0 1.0
out = df.stack(0).reset_index()
out.columns = ['Occ_s','Occ_T','Score']
print (out)
Occ_s Occ_T Score
0 3d modeling 3Dstudio 1.0
1 3d modeling Accountancy 0.0
2 3d modeling Cooking 0.0
3 IC auditor 3Dstudio 0.0
4 IC auditor Accountancy 1.0
5 IC auditor Cooking 1.0
6 Chef 3Dstudio 0.0
7 Chef Accountancy 1.0
8 Chef Cooking 1.0Numpy解决方案:
a = np.repeat(data_k_T.index, len(data_k_T.columns))
b = np.tile(data_k_T.columns, len(data_k_T))
c = dist_out.ravel()
out = pd.DataFrame({'Occ_s':a, 'Occ_T':b, 'Score':c})
print (out)
Occ_s Occ_T Score
0 3d modeling 3Dstudio 1.0
1 3d modeling Accountancy 0.0
2 3d modeling Cooking 0.0
3 IC auditor 3Dstudio 0.0
4 IC auditor Accountancy 1.0
5 IC auditor Cooking 1.0
6 Chef 3Dstudio 0.0
7 Chef Accountancy 1.0
8 Chef Cooking 1.0https://stackoverflow.com/questions/51703019
复制相似问题