我有一个2D数组,我想要计算每一列之间的平均距离,同时考虑到每一行.
例如,如果我有2D数组:
2 2 3
4 2 5
1 5 2
我希望计算列1和2之间跨越所有行、1和3跨所有行、2和3跨所有行之间的平均距离。
跨列1和列2的平均距离是( |2-2| + |4-2| + |1-5| ) / 3
,它等于2。
有能实现这一目标的numpy函数吗?
发布于 2017-10-26 22:05:08
像这样吗?
import numpy as np
x = np.array([[2,2,3],[4,2,5],[1,5,2]])
def calc(cols):
return np.mean(np.abs(np.diff(x[:, cols])))
print(calc([0,1]))
退出:
2.0
还应考虑:
import itertools
print(list(itertools.combinations(range(x.shape[1]), 2))) # outer list because using py3
退出:
[(0, 1), (0, 2), (1, 2)]
发布于 2017-10-27 06:59:33
我建议这样做:
from scipy.spatial.distance import pdist
m, n = in_arr.shape
pdist(in_arr.T, 'cityblock') / m
Out: array([ 2. , 1. , 2.33333333])
如果您想知道哪个距离与哪一对相关,请使用:
np.stack(np.triu_indices(n, 1))
Out:
array([[0, 0, 1],
[1, 2, 2]], dtype=int32)
这应该比使用for
循环或itertools
快得多。
https://stackoverflow.com/questions/46964459
复制相似问题