-1

Having numpy array like that:

a = np.array([35,2,160,56,120,80,1,1,0,0,1])

I want to subtract custom value (for example, 5) from first element of the array. Basically it can be done like:a[0] - 5

But how can I apply this result to the initial array and replace the first value with the answer?

Thanks!

Keithx
  • 2,994
  • 15
  • 42
  • 71

1 Answers1

2

You can use:

a[0] -= 5  # use -=

This will turn a into:

>>> a = np.array([35,2,160,56,120,80,1,1,0,0,1])
>>> a[0] -= 5
>>> a
array([ 30,   2, 160,  56, 120,  80,   1,   1,   0,   0,   1])

For most operations (+, -, *, /, etc.), there is an "inplace" equivalent (+=, -=, *=, /=, etc.) that will apply that operation with the right operand and store it back.

Note that if you want to subtract all elements, you should not use a Python for loop, there are more efficient ways for that.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555