首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用距离矩阵计算Pandas Dataframe中行之间的距离

使用距离矩阵计算Pandas Dataframe中行之间的距离
EN

Stack Overflow用户
提问于 2013-12-01 01:26:29
回答 3查看 28.1K关注 0票数 13

我有以下熊猫DataFrame:

代码语言:javascript
复制
In [31]:
import pandas as pd
sample = pd.DataFrame({'Sym1': ['a','a','a','d'],'Sym2':['a','c','b','b'],'Sym3':['a','c','b','d'],'Sym4':['b','b','b','a']},index=['Item1','Item2','Item3','Item4'])
In [32]: print(sample)
Out [32]:
      Sym1 Sym2 Sym3 Sym4
Item1    a    a    a    b
Item2    a    c    c    b
Item3    a    b    b    b
Item4    d    b    d    a

我想找到一种优雅的方法来根据这个距离矩阵得到每个Item之间的距离:

代码语言:javascript
复制
In [34]:
DistMatrix = pd.DataFrame({'a': [0,0,0.67,1.34],'b':[0,0,0,0.67],'c':[0.67,0,0,0],'d':[1.34,0.67,0,0]},index=['a','b','c','d'])
print(DistMatrix)
Out[34]:
      a     b     c     d
a  0.00  0.00  0.67  1.34
b  0.00  0.00  0.00  0.67
c  0.67  0.00  0.00  0.00
d  1.34  0.67  0.00  0.00 

例如,将Item1Item2进行比较将比较aaab -> accb --使用距离矩阵,这将是0+0.67+0.67+0=1.34

理想输出:

代码语言:javascript
复制
       Item1   Item2  Item3  Item4
Item1      0    1.34     0    2.68
Item2     1.34    0      0    1.34
Item3      0      0      0    2.01
Item4     2.68  1.34   2.01    0
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-01 01:53:39

这样做的工作量是所需的两倍,但在技术上也适用于非对称距离矩阵(无论这是什么意思)。

代码语言:javascript
复制
pd.DataFrame ( { idx1: { idx2:sum( DistMatrix[ x ][ y ]
                                  for (x, y) in zip( row1, row2 ) ) 
                         for (idx2, row2) in sample.iterrows( ) } 
                 for (idx1, row1 ) in sample.iterrows( ) } )

您可以通过将其分片编写来使其更具可读性:

代码语言:javascript
复制
# a helper function to compute distance of two items
dist = lambda xs, ys: sum( DistMatrix[ x ][ y ] for ( x, y ) in zip( xs, ys ) )

# a second helper function to compute distances from a given item
xdist = lambda x: { idx: dist( x, y ) for (idx, y) in sample.iterrows( ) }

# the pairwise distance matrix
pd.DataFrame( { idx: xdist( x ) for ( idx, x ) in sample.iterrows( ) } )
票数 5
EN

Stack Overflow用户

发布于 2016-07-05 22:08:44

这是一个老问题,但是有一个Scipy函数可以做到这一点:

代码语言:javascript
复制
from scipy.spatial.distance import pdist, squareform

distances = pdist(sample.values, metric='euclidean')
dist_matrix = squareform(distances)

pdist对Numpy矩阵进行操作,DataFrame.values是数据帧的底层Numpy NDarray表示。metric参数允许您从几个内置距离度量中选择一个,或者您可以传入任何二进制函数以使用自定义距离。它非常强大,而且,根据我的经验,速度非常快。结果是一个“平面”数组,它只包含距离矩阵的上三角形(因为它是对称的),不包括对角线(因为它总是0)。然后,squareform将这个展平的形式转换为一个完整的矩阵。

docs提供了更多信息,包括许多内置距离函数的数学摘要。

票数 29
EN

Stack Overflow用户

发布于 2017-09-13 02:13:55

对于大数据,我找到了一种快速的方法。假设您的数据已经是名为的np.array格式。

代码语言:javascript
复制
from sklearn.metrics.pairwise import euclidean_distances
dist = euclidean_distances(a, a)

下面是一个实验,比较两种方法所需的时间:

代码语言:javascript
复制
a = np.random.rand(1000,1000)
import time 
time1 = time.time()
distances = pdist(a, metric='euclidean')
dist_matrix = squareform(distances)
time2 = time.time()
time2 - time1  #0.3639109134674072

time1 = time.time()
dist = euclidean_distances(a, a)
time2 = time.time()
time2-time1  #0.08735871315002441
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20303323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档