This can be done with list comprehension in a simple one-liner.
Say you have a list of lists:
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
and you want to replace all occurrences of 2
with 4
:
[[_el if _el != 2 else 4 for _el in _ar] for _ar in a]
Another option is to use numpy's where
function. From the docstring:
where(condition, [x, y])
Return elements, either from x
or y
, depending on condition
.
So, in your case (say you'd like again to replace all 2
with 4
):
import numpy as np
a = np.array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
np.where(a==2, 4, a)
If you want to replace several values in one go, you could do something like this:
Say you'd like to replace 1
with 3
and 3
with 5
:
ix=np.isin(array, [1,3])
vc=np.vectorize(lambda x: 3 if x == 1 else 5)
np.where(ix, vc(array), array)
If you have more than 2 values to replace, say you want to map the list [1,3,5]
to [3, 5, -3]
, then you can define a simple function like:
old_vals = [1,3,5]
new_vals = [3, 5, -3]
def switch_val(x):
return new_vals[old_vals.index(x)] if x in old_vals else x
and so:
vc=np.vectorize(switch_val)
vc(array)
where we vectorized the function.
Hope that helped and happy coding!