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!
解决方案
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.