pythonnumpy

Calculate relative difference of elements in a 1D numpy array


Say I have a 1D numpy-array given by np.array([1,2,3]).

Is there a built-in command for calculating the relative difference between each element and display it in a 2D-array? The result would then be given by

np.array([[0,-50,-100*2/3], [100,0,-100*1/3], [200,50,0]])

Alternatively I would have to use a for-loop.


Solution

  • Use numpy broadcasting:

    a = np.array([1,2,3])
    
    out = (a[:, None]-a)/a*100
    

    Output:

    array([[  0.        , -50.        , -66.66666667],
           [100.        ,   0.        , -33.33333333],
           [200.        ,  50.        ,   0.        ]])