繁体   English   中英

python & pandas:迭代 DataFrame 两次

[英]python & pandas: iterating over DataFrame twice

对 DataFrame 的每一行进行 mahalanobis 计算,并与 DataFrame 中的其他每一行都有距离。 它看起来像这样:

import pandas as pd
from scipy import linalg
from scipy.spatial.distance import mahalanobis
from pprint import pprint

testa = { 'pid': 'testa', 'a': 25, 'b': .455, 'c': .375 }
testb = { 'pid': 'testb', 'a': 22, 'b': .422, 'c': .402 }
testc = { 'pid': 'testc', 'a': 11, 'b': .389, 'c': .391 }

cats = ['a','b','c']
pids = pd.DataFrame([ testa, testb, testc ])
inverse = linalg.inv(pids[cats].cov().values)
distances = { pid: {} for pid in pids['pid'].tolist() }

for i, p in pids.iterrows():
    pid = p['pid']
    others = pids.loc[pids['pid'] != pid]
    for x, other in others.iterrows():
        otherpid = other['pid']
        d = mahalanobis(p[cats], other[cats], inverse) ** 2
        distances[pid][otherpid] = d

pprint(distances)

它适用于这里的三个测试用例,但在现实生活中它会运行大约 2000-3000 行,并且使用这种方法需要很长时间。 我对 Pandas 比较陌生,我真的更喜欢 python 而不是 R,所以我想把它清理干净。

我怎样才能使这更有效?

对 DataFrame 的每一行进行 mahalanobis 计算,并与 DataFrame 中的其他每一行都有距离。

这基本上在sklearn.metrics.pairwise.pairwise_distances得到解决,因此是否可以手动更有效地进行处理是值得怀疑的。 因此,在这种情况下,如何

from sklearn import metrics

>>> metrics.pairwise.pairwise_distances(
    pids[['a', 'b', 'c']].as_matrix(),
    metric='mahalanobis')
array([[ 0.        ,  2.15290501,  3.54499647],
       [ 2.15290501,  0.        ,  2.62516666],
       [ 3.54499647,  2.62516666,  0.        ]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM