HalfPintBoy - 3 years ago 95
Python Question

# Subtract from first value in numpy array

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download