5argon
5argon

Reputation: 3863

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.

Upvotes: 6

Views: 8615

Answers (3)

yevgeniy
yevgeniy

Reputation: 908

I have a faster implementation than np.where, also a one-liner improvement on @vindvaki:

a*=((a>100)*1.2+(a<100)*0.8)

With it you don't need to make an extra function call, and you can also add arbitrarily many modifiers using boolean logic multipliers. This one-liner will save you some computational time if your arrays get big (like 10**8 big).

Upvotes: 4

vindvaki
vindvaki

Reputation: 534

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

Upvotes: 8

5argon
5argon

Reputation: 3863

np.where is the answer. I spend time messing with np.place without knowing its existence.

Upvotes: 1

Related Questions