Home > Blockchain >  Get array of values from iterative subtraction of subsequent values within the array
Get array of values from iterative subtraction of subsequent values within the array

Time:08-01

I have an array as follows:

import numpy as np

my_array = np.array([1,2,3])

Now, given a starting value, for example 100, I would like to calculate the array that is formed by subtracting the subsequent value from the result of the previous subtraction. That is, I would like to get the result of:

100 - 1, 99 - 2, 97 - 3

That is, [99, 97, 94].

I have tried the following.

import numpy as np

my_array = np.array([1,2,3])


def resta_iterativa(value):
    result = []
    for i in my_array:
        substraction = value - i
        result.append(substraction)
        return result
        

The goal is to achieve an efficient code that works.

CodePudding user response:

You can use numpy.ufunc.accumulate:

import numpy as np
arr = np.array([1,2,3])
arr[0] = 100 - arr[0]
np.subtract.accumulate(arr)

Output:

array([99, 97, 94])
  • Related