Skip to content Skip to sidebar Skip to footer

Is There A More Efficient Way Generate An Array From Another Array With A Little Bit Complex Rule?

I am trying to compute a distance between an element and a starting point in an array. Here is an array assume the element (0,1) is a starting point which has the highest value cu

Solution 1:

You're calculating the Manhattan distance (the x-distance plus the y-distance) from a target point for each point.

You can use a numpy function to do it in one step, given the target coordinates and the shape of the array:

target = (0, 1)
np.fromfunction(lambda x,y: np.abs(target[0]-x) + np.abs(target[1]-y), ds.shape)    

Result:

[[1. 0. 1.]
 [2. 1. 2.]
 [3. 2. 3.]]

Demo: https://repl.it/repls/TrustyUnhappyFlashdrives

Post a Comment for "Is There A More Efficient Way Generate An Array From Another Array With A Little Bit Complex Rule?"