Reputation: 789
I want to add a certain number to values of my arrays, with a maximum capping out at 255, but only in cases where the number in the array does not match 0.
Imagine the value I want to add to each number in my array is 20, except if number is 0
#The array to which I want to add a number based on value:
v=array([0,0,0,0,117,119,120,121,16,1,16,10,245,0,0,0,4,5])
value=20
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
#Results in the following array
array([20,20,20,20,137,139,140,141,36,21,36,30,255,20,20,20,24,25])
This works, but also adds when the number is 0. However, I want to have a statement in there, that adds 20 in all cases, except if the number in the array is 0! Expected outcome:
array([0,0,0,0,137,139,140,141,36,21,36,30,255,0,0,0,24,25])
Wasn't able to find a good solution or figure out how.
Upvotes: 0
Views: 125
Reputation: 2243
Use these two lines to achieve your expected output
v[(v!=0)] += 20
v[v > 255] = 255
Complete Code:
v= np.array([0,0,0,0,117,119,120,121,16,1,16,10,245,0,0,0,4,5])
value=20
lim = 255
v[v!=0] += value
v[v>lim] = lim
print(v)
>> [ 0 0 0 0 137 139 140 141 36 21 36 30 255 0 0 0 24 25]
Upvotes: 1
Reputation: 36340
I would do it following way:
import numpy as np
v = np.array([0,0,0,0,117,119,120,121,16,1,16,10,245,0,0,0,4,5])
value = 20
lim = 255
v += (v!=0)*value
v = np.clip(v, None, lim)
print(list(v))
output
[0, 0, 0, 0, 137, 139, 140, 141, 36, 21, 36, 30, 255, 0, 0, 0, 24, 25]
Explanation: I treat boolean array of where there are non-zero as array of 0
s and 1
s, thus by multiplying by value
I get value to add for each element, then I use numpy.clip to replace values beyond lim
.
Upvotes: 1
Reputation: 170
Replace v[v <= lim] += value
with v[(v != 0) & (v <= lim)] += value
Upvotes: 1