0

I have an array in numpy:

[1  2  3]
[4  5  6]
[7  8  9]
[10 11 12]

I would like to add 100 to all values that are greater than or equal to 3 and less than or equal to 8. How can I do this?

1
  • 2
    Welcome to stackoverflow! Take a look here to improve your question. Please share the code of your tries so we can help you. Commented Feb 17, 2020 at 19:26

3 Answers 3

2

You could create a mask based on your criteria and then add 100 to each value.

arr = np.array([[1,  2,  3],
                [4,  5,  6],
                [7,  8, 9],
                [10, 11, 12]])
mask = (arr >= 3) & (arr <= 8)
arr[mask] += 100
Sign up to request clarification or add additional context in comments.

Comments

0

You could do something like this:

>>> import numpy as np
>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
>>> (x >= 3) * (x <= 8) * 100
array([[  0,   0, 100],
       [100, 100, 100],
       [100, 100,   0],
       [  0,   0,   0]])

and then add that to your array. Note that (x >= 3) * (x <= 8) contains boolean values that are cast to 0 or 1 once you multiply them with the integer 100.

Comments

0

Try this :

>>> a[np.where((8>=a) & (a>=3))]+=100
>>> a
array([[  1,   2, 103],
       [104, 105, 106],
       [107, 108,   9],
       [ 10,  11,  12]])

where a is :

array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

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.