Python 如何在numpy数组中查找元素之间的距离?

Python 如何在numpy数组中查找元素之间的距离?,python,arrays,numpy,Python,Arrays,Numpy,例如,我有这样的数组z: 数组([1,0,1,0,0,0,1,0,0,1]) 如何在此数组中查找两个连续1s之间的距离?(以0s的数量计量) 例如,在z数组中,这样的距离是: [1, 3, 2] 我有这样的代码: distances = [] prev_idx = 0 for idx, element in enumerate(z): if element == 1: distances.append(idx - prev_idx) prev_

例如,我有这样的数组
z
数组([1,0,1,0,0,0,1,0,0,1])

如何在此数组中查找两个连续
1
s之间的距离?(以
0
s的数量计量)

例如,在
z
数组中,这样的距离是:

[1, 3, 2]
我有这样的代码:

distances = []
prev_idx = 0
for idx, element in enumerate(z):
    
    if element == 1:
        distances.append(idx - prev_idx)
        prev_idx = idx

distances = np.array(distances[1:]) - 1
这种操作能在没有for-loop的情况下完成吗?也许能以更有效的方式完成

UPD

@warped答案中的解决方案在一维情况下运行良好。
但是如果
z
将是
2D
-数组,就像
np.array([z,z])

您可以使用np.where来查找,然后使用np.diff来获得距离:

q=np.where(z==1)
np.diff(q[0])-1
输出:

编辑: 对于二维阵列:

可以使用具有1的位置的曼哈顿距离的最小值(减1)来获得中间的零数:

def manhattan_distance(a, b):
    return np.abs(np.array(a) - np.array(b)).sum()

zeros_between = []

r, c = np.where(z==1)
coords = list(zip(r,c))

for i, c in enumerate(coords[:-1]):
    
    zeros_between.append(
    np.min([manhattan_distance(c, coords[j])-1 for j in range(i+1, len(coords))]))

如果不想使用for,可以使用np.where和np.roll

import numpy as np
x = np.array([1, 0, 1, 0, 0, 0, 1, 0, 0, 1])
pos = np.where(x==1)[0] #pos = array([0, 2, 6, 9])
shift = np.roll(pos,-1) # shift = array([2, 6, 9, 0])
result = ((shift-pos)-1)[:-1] 
#shift-pos = array([ 2,  4,  3, -9])
#(shif-pos)-1 = array([ 1,  3,  2, -10])
#((shif-pos)-1)[:-1] = array([ 1,  3,  2])
print(result)


在2D情况下,此解决方案更难实现。考虑相同的解决方案:<代码> NexZZ=NP.Stand([Z,Z])< /C> > KeNeBeKARZYMATOVO,请参阅我编辑的一种方法,该方法在2DIS中更有效,只是将<代码> 1D < /C>解决方案与for循环结合起来更有效?在您的示例中,
coords
变量是什么?对不起,忘了在中输入coords定义。至于多次使用1d解决方案:这将不起作用。当您单独查看这些线时,在2d中相邻的线将相距很远。
import numpy as np
x = np.array([1, 0, 1, 0, 0, 0, 1, 0, 0, 1])
pos = np.where(x==1)[0] #pos = array([0, 2, 6, 9])
shift = np.roll(pos,-1) # shift = array([2, 6, 9, 0])
result = ((shift-pos)-1)[:-1] 
#shift-pos = array([ 2,  4,  3, -9])
#(shif-pos)-1 = array([ 1,  3,  2, -10])
#((shif-pos)-1)[:-1] = array([ 1,  3,  2])
print(result)