0

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]) 

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help! That was exactly what I was looking for.
1

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.