Search code examples
pythonarraysnumpyloopsdifference

Finding differences in arrays


I have an array in python which consists of distances in meters (chainage) between electric poles. Here’s a sample

d=([0, 98, 198, 300, 400, 500, 600, 700, 800, 900, 997, 1102, 1187, 1282, 1382, 1480, 1570, 1670, 1775, 1885, 1980, 2083, 2178])

I want to write a script to compute the difference (section length) at every 1000m or close to 1000m but not exceeding 1000m.

Here’s an example

  • Section1 = 997 - 0

  • Section2 = 1980 - 997

  • Section3 = 2178 - 1980

The result should be in array

Section = ([997, 983, 198])

I’m a beginner in python. I’m still learning. I have not attached any code because I do not have any idea on where to start.


Solution

  • Since you ask for a numpy solution, let's do away with those for loops:

    d=np.array([0, 98, 198, 300, 400, 500, 600, 700, 800, 900, 997, 1102, 1187, 1282, 1382, 1480, 1570, 1670, 1775, 1885, 1980, 2083, 2178])
    
    def func(d, k = 1000):
        insert = (np.arange(d.max() // k) + 1) * k                   #intermediate points
        vals = np.r_[d[0], d[np.searchsorted(d, insert) - 1], d[-1]] #values below the intermediate points
        return np.diff(vals)                                         #difference between the intermediate points
    
    func(d)
    Out[]: array([997, 983, 198])