2

Simple example for replacing values in the array according to a list:

import numpy as np

l = [1,3,4,15]
a = np.array([1,1,2,4,6,7,8,9,1,2,3,4,89,12,23,3,4,10,15])
for element in l:
     a = np.where(a == element, 0, a)

Since this is rather slow, I'm looking for a faster alternative, that scales well.

zacha2
  • 223
  • 2
  • 16

3 Answers3

2

You can use np.where with np.in1d:

np.where(np.in1d(a, l), 0, a)

array([ 0,  0,  2,  0,  6,  7,  8,  9,  0,  2,  0,  0, 89, 12, 23,  0,  0,
       10,  0])
yatu
  • 86,083
  • 12
  • 84
  • 139
1

Use numpy.where with numpy.isin:

np.where(np.isin(a, l), 0, a)

Output:

array([ 0,  0,  2,  0,  6,  7,  8,  9,  0,  2,  0,  0, 89, 12, 23,  0,  0,
       10,  0])
Chris
  • 29,127
  • 3
  • 28
  • 51
1

Use np.where with np.isin:

a = np.where(np.isin(a, l), 0, a)
print(a)

Output:

[ 0  0  2  0  6  7  8  9  0  2  0  0 89 12 23  0  0 10  0]

If your version of numpy is small than 1.13.0, use @yatu's answer.

Since as mentioned in the documentation's notes:

New in version 1.13.0.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114