0

I tried to change values in an array when it is in some condition.

For example, I would to like to add 30, when the vlaues are only higher than 10.

So, I tried as follows:

x = np.arange(15)
x[x>10] = x + 30

I shows "ValueError: NumPy boolean array indexing assignment cannot assign 15 input values to the 4 output values where the mask is true".

Also I tried if else and np.where methods but they also does not work. They seem work only when replacing quantity is a certain value such as 30, not an equation as x + 30.

Any idea or help would be really appreciated.

Thank you,

Isaac

3 Answers 3

3

You can use the in-place operator += to easily achieve this:

x[x>10] += 30
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Graipher,
1

Subset the array before and after the assignment so they have the same length:

x[x > 10] = x[x > 10] + 30
x
# array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 41, 42, 43, 44])

Or use np.add.at:

np.add.at(x, x > 10, 30)
x
# array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 41, 42, 43, 44])

Use np.where, you can do:

np.where(x > 10, x + 30, x)
# array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 41, 42, 43, 44])

1 Comment

Thank you very much Psidom.
1

Remember a Boolean array can also be given numerical operations

x += (x > 10) * 30

1 Comment

Thank you very myuch FHTMitchell.

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.