Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy conditional multiply data in array (if true multiply A, false multiply B)

Say I have a large array of value 0~255. I wanted every element in this array that is higher than 100 got multiplied by 1.2, otherwise, got multiplied by 0.8.

It sounded simple but I could not find anyway other than iterate through all the variable and multiply it one by one.

like image 392
5argon Avatar asked Dec 20 '22 01:12

5argon


1 Answers

If arr is your array, then this should work:

arr[arr > 100] *= 1.2
arr[arr <= 100] *= 0.8

Update: As pointed out in the comments, this could have the undesired effect of the first step affecting what is done in the second step, so we should instead do something like

# first get the indexes we of the elements we want to change
gt_idx = arr > 100
le_idx = arr <= 100
# then update the array
arr[gt_idx] *= 1.2
arr[le_idx] *= 0.8
like image 141
vindvaki Avatar answered Dec 26 '22 10:12

vindvaki