Python 熊猫:数值的矩阵计算
我有这样的数据帧:Python 熊猫:数值的矩阵计算,python,pandas,simhash,Python,Pandas,Simhash,我有这样的数据帧: apple aple apply apple 0 0 0 aple 0 0 0 apply 0 0 0 我想计算字符串距离,例如apple->aple等。我的最终结果如下: apple aple apply apple 0 32 14 aple 32 0 30 apply 14 30 0
apple aple apply
apple 0 0 0
aple 0 0 0
apply 0 0 0
我想计算字符串距离,例如apple->aple等。我的最终结果如下:
apple aple apply
apple 0 32 14
aple 32 0 30
apply 14 30 0
目前这是我正在使用的代码(但对于大数据来说速度非常慢):
有人能帮我有效地计算距离吗 一个想法-由于输出是对称的,通过对每一对进行迭代,您将计算每一对两次。此外,还可以跳过元素与自身之间的比较。因此,至少要减少计算的数量,你可以这样做——使用itertools只计算成对的距离,然后使用pandas来填充其余的距离
from itertools import combinations
from collections import defaultdict
data = df.index
output = defaultdict(dict)
for a,b in combinations(data, 2):
output[a][b] = Simhash(a).distance(Simhash(b))
for a in data:
output[a][a] = 0
df = pd.DataFrame(output)
df = df.fillna(df.T)
你必须在一个更大的框架上进行测试,但我认为它会比你正在做的更快,并且应该给出相同的答案
In [84]: df
Out[84]:
aple apple apply
aple 0 32 30
apple 32 0 14
apply 30 14 0
In [84]: df
Out[84]:
aple apple apply
aple 0 32 30
apple 32 0 14
apply 30 14 0