使用python diff()的数组中所有1D点之间的差异?

时间:2014-01-08 18:07:09

标签: python numpy scipy difference

寻找关于如何编写函数(或者可以推荐已经存在的函数)的提示,该函数计算数组中所有条目之间的差异,即diff()的实现,但是对于数组中的所有条目组合不只是连续的对。

这是我想要的一个例子:

# example array
a = [3, 2, 5, 1]

现在我们要应用一个函数来返回所有条目组合之间的差异。现在假设length(a) == 4意味着组合的总数是,对于N = 4; N *(N-1)* 0.5 = 6(如果a的长度为5,则组合的总数将为10,依此类推)。因此该函数应该为向量a返回以下内容:

result = some_function(a)
print result
array([-1, 2, -2, 3, -1, -4])

因此'函数'与pdist类似,但不是计算欧几里德距离,而应简单地计算沿一个轴的笛卡尔坐标之间的差值,例如:如果我们假设a中的条目是坐标,则为z轴。可以注意到,我需要每个差异的符号来理解每个点所在的轴的哪一侧。

感谢。

2 个答案:

答案 0 :(得分:4)

这样的东西?

>>> import itertools as it
>>> a = [3, 2, 5, 1]
>>> [y - x for x, y in it.combinations(a, 2)]
[-1, 2, -2, 3, -1, -4]

答案 1 :(得分:1)

所以我尝试了wim和Joe提出的方法(以及Joe和wim的综合建议),这就是我想出来的:

import itertools as it
import numpy as np

a = np.random.randint(10, size=1000)

def cartesian_distance(x):
    return np.subtract.outer(x,x)[np.tril_indices(x.shape[0],k=-1)]

%timeit cartesian_distance(a)
%timeit [y - x for x, y in it.combinations(a, 2)]

10 loops, best of 3: 97.9 ms per loop
1 loops, best of 3: 333 ms per loop

对于较小的条目:

a = np.random.randint(10, size=10)

def cartesian_distance(x):
    return np.subtract.outer(x,x)[np.tril_indices(x.shape[0],k=-1)]

%timeit cartesian_distance(a)
%timeit [y - x for x, y in it.combinations(a, 2)]

10000 loops, best of 3: 78.6 µs per loop
10000 loops, best of 3: 40.1 µs per loop