3

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).

1
  • 2
    You seem to have a 3D array. Did you intend for it to be 3D? The length-1 dimension and the reference to "columns" suggests you might have intended to have something 2D. Commented Jan 30, 2017 at 23:18

2 Answers 2

8

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]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This solution is exactly what I needed.
3

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.