picachu
picachu

Reputation: 26

Perform operation in NumPy array except for some values

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.

Upvotes: 1

Views: 252

Answers (1)

yatu
yatu

Reputation: 88305

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

Upvotes: 1

Related Questions