Stellar Streams
Stellar Streams

Reputation: 57

fastest way to replace values in an array with the value in the same position in another array if they match a condition

I'm trying this syntaxis to replace values in an array with the value in the same position in another array if they match a condition:

array[array>limit]=other_array[array>limit]

It works but I think I might be doing it the hard way. Any thoughts?

Upvotes: 1

Views: 840

Answers (2)

Alain T.
Alain T.

Reputation: 42143

You can do it in a single assignment using argwhere() to get the indices to replace but your approach is faster assuming you don't evaluate the condition twice:

import numpy as np

array1 = np.arange(100)
array2 = np.arange(1000,1100)

condition = array1%3==0 # avoid doing this twice
array1[condition] = array2[condition]

output:

print(array1)

[1000    1    2 1003    4    5 1006    7    8 1009   10   11 1012   13
   14 1015   16   17 1018   19   20 1021   22   23 1024   25   26 1027
   28   29 1030   31   32 1033   34   35 1036   37   38 1039   40   41
 1042   43   44 1045   46   47 1048   49   50 1051   52   53 1054   55
   56 1057   58   59 1060   61   62 1063   64   65 1066   67   68 1069
   70   71 1072   73   74 1075   76   77 1078   79   80 1081   82   83
 1084   85   86 1087   88   89 1090   91   92 1093   94   95 1096   97
   98 1099]

Upvotes: 0

Alexander
Alexander

Reputation: 109696

Use np.where:

Parameters

condition: array_like, bool

   Where True, yield x, otherwise yield y.

x, y: array_like

   Values from which to choose. x, y and condition need to be broadcastable to some shape.

Returns

out: ndarray

   An array with elements from x where condition is True, and elements from y elsewhere.

Example:

a1 = np.array([3, 2, 4, 1])
a2 = a1 + 10

limit = 2
>>> np.where(a1 > limit, a2, a1)
array([13,  2, 14,  1])

Upvotes: 2

Related Questions