So I have an example array, say:
import numpy as np
np.array([[[ 85, 723]],
[[ 86, 722]],
[[ 87, 722]],
[[ 89, 724]],
[[ 88, 725]],
[[ 87, 725]]])
What I want to do is subtract a number from only the second column, say 10 for example. What I hope to have the output look like is something like this:
np.array([[[ 85, 713]],
[[ 86, 712]],
[[ 87, 712]],
[[ 89, 714]],
[[ 88, 715]],
[[ 87, 715]]])
I have tried using np.subtract, but it does not support subtraction along an axis (at least to my knowledge).
Slice and subtract -
a[...,1] -= 10
This would work for arrays of any number of dimensions to subtract from the second column.
Sample run -
In [582]: a
Out[582]:
array([[[30, 23]],
[[36, 88]],
[[27, 15]],
[[38, 61]],
[[79, 14]]])
In [583]: a[...,1] -= 10
In [584]: a
Out[584]:
array([[[30, 13]],
[[36, 78]],
[[27, 5]],
[[38, 51]],
[[79, 4]]])
Do an in-place subtraction on the specified index (in this case I index the whole column):
>>> arr[:, :, 1] -= 10
>>> arr
array([[[ 85, 713]],
[[ 86, 712]],
[[ 87, 712]],
[[ 89, 714]],
[[ 88, 715]],
[[ 87, 715]]])
Also works with np.subtract when you specify out:
>>> np.subtract(arr[:, :, 1], 10, out=arr[:, :, 1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With