Reputation: 191
I want to scale specific values (e.g. lager than 5) of an numpy array numbers by a multiplier (e.g. 2). I know I can achieve this by a loop, but I wanted to avoid loops. I think I can achieve this somehow with a numpy mask but I am not sure how to implement it. In order to demonstrate what I aim to achieve I used the imaginary function scale_array.
Here is a minimal working example
import numpy as np
numbers = np.array([-3, 5, 2, -1, -15, 10])
mask = np.abs(numbers) > 5
numbers_scaled = scale_array(array=numbers, mask=mask, scale_factor=2)
print(numbers_scaled) # np.array([-3, 5, 2, -1, -30, 20])
Upvotes: 0
Views: 393
Reputation: 561
As you write, mask = np.abs(numbers) > 5
gives you the locations you want to scale.
Simply doing numbers[mask] *= 2
should do the trick :)
Upvotes: 1
Reputation: 13255
Directly assign masked values multiplied by 2 to original array as:
numbers = np.array([-3, 5, 2, -1, -15, 10])
mask = np.abs(numbers) > 5
numbers[mask] = numbers[mask]*2
numbers
array([ -3, 5, 2, -1, -30, 20])
Upvotes: 1