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?
asked Feb 17, 2020 at 19:21
redwytnblak
1631 gold badge3 silver badges11 bronze badges
-
2Welcome to stackoverflow! Take a look here to improve your question. Please share the code of your tries so we can help you.Carlo Zanocco– Carlo Zanocco2020年02月17日 19:26:17 +00:00Commented Feb 17, 2020 at 19:26
3 Answers 3
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
answered Feb 17, 2020 at 19:25
Maximilian Peters
31.8k12 gold badges95 silver badges102 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Feb 17, 2020 at 19:27
Michael H.
3,5232 gold badges27 silver badges31 bronze badges
Comments
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]])
answered Feb 17, 2020 at 19:30
Arkistarvh Kltzuonstev
6,9687 gold badges32 silver badges62 bronze badges
Comments
lang-py