Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 所有行到单行的欧氏距离_Python_Pandas_Scikit Learn - Fatal编程技术网

Python 所有行到单行的欧氏距离

Python 所有行到单行的欧氏距离,python,pandas,scikit-learn,Python,Pandas,Scikit Learn,我有一个数据集,它给出了一些歌曲的值,例如: acousticness danceability energy instrumentalness key liveness loudness 0 0.223 0.780 0.72 0.111 1 0.422 0.231 1 0.4 0.644 0.88 0.555 0.5 0.66 0.

我有一个数据集,它给出了一些歌曲的值,例如:

    acousticness danceability energy instrumentalness key  liveness  loudness 
0        0.223      0.780      0.72       0.111        1     0.422    0.231
1        0.4        0.644      0.88       0.555        0.5   0.66     0.555
2        0.5        0.223      0.145      0.76         0     0.144    0.567
.
.
.
我想使用欧几里德距离查找数字上与另一首歌曲最接近的歌曲/行,例如歌曲
0
。因此,我想获得如下结果:

    acousticness danceability energy instrumentalness key  liveness  loudness Euclidean to song 0
0        0.223      0.780      0.72       0.111        1     0.422    0.231       0
1        0.4        0.644      0.88       0.555        0.5   0.66     0.555      1.334
2        0.5        0.223      0.145      0.76         0     0.144    0.567     1.442
.
.
.

您尝试执行的通常步骤是使用sklearn中的一个,例如,并使用它构建一个相似性矩阵:

from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances

cosine_similarity(df)
array([[1.        , 0.86597679, 0.38431913],
       [0.86597679, 1.        , 0.71838491],
       [0.38431913, 0.71838491, 1.        ]])
这将为您提供一个带有表示数据帧索引的索引的方阵


与单个项目的相似性

如果您只对与特定歌曲的相似性感兴趣,例如歌曲
0
,则可以将第二个数组指定为,以便使用输入矩阵中的所有项和给定项获得相似性

既然你提到了欧几里德距离,这里有一个是使用sklearn的
欧几里德距离的。注意,由于我们有距离,所以我们必须从
1
中减去结果。如果我们想要实际距离,我们可以只保留结果数组:

1-euclidean_distances(df, df.to_numpy()[0,None])
array([[ 1.        ],
       [-0.16977006],
       [-1.15823261]]) 
对于距离,只需:

euclidean_distances(df, df.to_numpy()[0,None])
array([[0.        ],
       [1.43266989],
       [2.64328432]])
要更新为新列,请执行以下操作:

df['Similarity with song 0'] = 1-euclidean_distances(df, df.to_numpy()[0,None]).squeeze()


我正在尝试查找与歌曲0最接近的歌曲,以便我可以按最接近的声音对它们进行排序。为什么您不在问题中包含这些细节@对不起,我应该说得更清楚。有没有办法做这样的事?
print(df)

   acousticness  danceability  energy  instrumentalness  key  liveness  \
0         0.223         0.780   0.720             0.111  1.0     0.422   
1         0.400         0.644   0.880             0.555  0.5     0.660   
2         0.500         0.223   0.145             0.760  0.0     0.144   

   loudness  Similarity with song 0  
0     0.231                1.000000  
1     0.555               -0.169770  
2     0.567               -1.158233