简体   繁体   English

numpy-在固定距离处计算数组中所有可能的差异

[英]Numpy - compute all possible differences in an array at fixed distance

Suppose I have an array, and I want to compute differences between elements at a distance Delta . 假设我有一个数组,并且我想计算距离为Delta元素之间的差异。 I can use numpy.diff(Array[::Delta-1]) , but this will not give all possible differences (from each possible starting point). 我可以使用numpy.diff(Array[::Delta-1]) ,但这不会给出所有可能的差异(从每个可能的起点)。 To get them, I can think of something like this: 为了得到它们,我可以想到这样的事情:

for j in xrange(Delta-1):
    NewDiff = numpy.diff(Array[j::Delta-1])
    if j==0:
        Diff = NewDiff
    else:
        Diff = numpy.hstack((Diff,NewDiff))

But I would be surprised if this is the most efficient way to do it. 但是,如果这是最有效的方法,我会感到惊讶。 Any idea from those familiar with the most exoteric functionalities of numpy ? 那些熟悉numpy最为公开的功能的人有什么想法吗?

The following function returns a two-dimensional numpy array diff which contains the differences between all possible combinations of a list or numpy array a . 以下函数返回二维numpy数组diff ,其中包含列表或numpy数组a所有可能组合之间的差异。 For example, diff[3,2] would contain the result of a[3] - a[2] and so on. 例如, diff[3,2]将包含a[3] - a[2] ,依此类推。

def difference_matrix(a):
    x = np.reshape(a, (len(a), 1))
    return x - x.transpose()

Update 更新资料

It seems I misunderstood the question and you are only asking for an the differences of array elements which are a certain distance d apart. 看来我误解了这个问题,您只是在问相隔一定距离d的数组元素的区别。 1) 1)

This can be accomplished as follows: 这可以通过以下方式完成:

>>> a = np.array([1,3,7,11,13,17,19])
>>> d = 2
>>> a[d:] - a[:-d]
array([6, 8, 6, 6, 6])

Have a look at the documentation to learn more about this notation. 查看文档以了解有关此符号的更多信息。

But, the function for the difference matrix I've posted above shall not be in vain. 但是,我上面发布的差矩阵的函数不会白费。 In fact, the array you're looking for is a diagonal of the matrix that difference_matrix returns. 实际上,您要查找的数组是difference_matrix返回的矩阵的对角线。

>>> a = [1,3,7,11,13,17,19]
>>> d = 2
>>> m = difference_matrix(a)
>>> np.diag(m, -d)
array([6, 8, 6, 6, 6])

1) Judging by your comment, this distance d is different than the Delta you seem to be using, with d = Delta - 1 , so that the distance between an element and itself is 0, and its distance to the adjacent elements is 1. 1)根据您的评论判断,此距离d与您似乎正在使用的Delta不同,其中d = Delta - 1 ,因此元素与其自身之间的距离为0,并且其与相邻元素之间的距离为1。

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

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