Home > Software engineering >  subtracting element of an array from next elements
subtracting element of an array from next elements

Time:02-02

I have a numpy array i want to subtract the previous number from the next number after fixing the first number and want to replace last number with zero

a=np.array([10,20,22,44])

expected output

np.array([10,10,2,0])

I tried with np.diff function but it misses the first number.Hope experts will suggest better solution.

CodePudding user response:

You want a custom output, so use a custom concatenation:

out = np.r_[a[0], np.diff(a[:-1]), 0]

Output: array([10, 10, 2, 0])

  • Related