1

Is there a simple way to lock/freeze an element within a Numpy Array. I would like to do several operations over a Numpy Array in python while keeping some specific values as they are originally.

for example,

if a have a Numpy Array a ;

[[ 1  3  4  5],
  [6  7  8  0],
  [9 10  11 2]]

and another Numpy Array b ;

[[2  0  4  10],
 [11 5  12  3],
 [6  8  7   9]]

and c = a+b but keeping the original values of 3, 8 and 2 in a.

My arrays are quite big and I would like a solution where I don't have to use a for loop, an if statement or something similar.

1 Answer 1

1

You can use np.isin to build a mask, and then np.where to populate from either a or a+b depending on on the result:

m = np.isin(a, [3,8,2])
c = np.where(m, a, a+b)

Or as @hpaulj suggests, you could also use where and out in np.add, which would modify a in-place:

np.add(a, b, where=~np.isin(a,[3,8,2]), out=a)

array([[ 3,  3,  8, 15],
       [17, 12,  8,  3],
       [15, 18, 18,  2]])
Sign up to request clarification or add additional context in comments.

2 Comments

You could also use the where (and out) of np.add.
Right nice suggestion @hpaulj :) Added it to the answer

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.