I have an array, for example:
array = np.array([[0,1,0,0,4,0,5,0,0],
[1,1,1,0,0,0,0,2,2],
[1,1,0,0,3,0,0,2,2],
[0,0,0,0,3,0,0,0,0],
[6,6,0,0,0,0,7,7,7]])
I also have a list, for example:
list = [0, 1, 2, 3, 7]
I want to remove (set to zero) all values in the array that do not appear in the list. For example:
newarray = [[0 1 0 0 0 0 0 0 0]
[1 1 1 0 0 0 0 2 2]
[1 1 0 0 3 0 0 2 2]
[0 0 0 0 3 0 0 0 0]
[0 0 0 0 0 0 7 7 7]
Here, the 4s, 5s, and 6s in the array have been replaced with 0s because they didn't appear in the list. My current solution is pretty slow using np.where() in a loop to remove all values in the array that don't appear in the list:
# get all unique values in array
unique_vals_in_array = np.unique(array)
# get all values in array that don't appear in list
vals_not_in_array = set(unique_vals_in_array) - set(list)
# On each loop, replace the values that do not appear in list with zero
for i in vals_not_in_array:
new_array = np.where(array==i,0,array)
If anyone has a more efficient, pythonic solution I'd appreciate it.