Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

python - How to find a distance between elements in numpy array?

For example, I have such array z: array([1, 0, 1, 0, 0, 0, 1, 0, 0, 1])

How to find a distances between two successive 1s in this array? (measured in the numbers of 0s)

For example, in the z array, such distances are:

[1, 3, 2]

I have such code for it:

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

Can this opeartion be done without for-loop and maybe in more efficient way?

UPD

The solution in the @warped answer works fine in 1-D case. But what if z will be 2D-array like np.array([z, z])?

question from:https://stackoverflow.com/questions/65873043/how-to-find-a-distance-between-elements-in-numpy-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use np.where to find the ones, and then np.diff to get the distances:

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

out:

array([1, 3, 2], dtype=int64)

edit:

for 2d arrays:

You can use the minimum of the manhattan distance (decremented by 1) of the positions that have ones to get the number of zeros inbetween:

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))]))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...