I want to find and replace multiple values in an 1D array / list with new ones.
In example for a list
a=[2, 3, 2, 5, 4, 4, 1, 2]
I woul
In vanilla Python, without the speed of numpy
or pandas
, this is one way:
a = [2, 3, 2, 5, 4, 4, 1, 2]
val_old = [1, 2, 3, 4, 5]
val_new = [2, 3, 4, 5, 1]
expected_a_new = [3, 4, 3, 1, 5, 5, 2, 3]
d = dict(zip(val_old, val_new))
a_new = [d.get(e, e) for e in a]
print a_new # [3, 4, 3, 1, 5, 5, 2, 3]
print a_new == expected_a_new # True
The average time complexity for this algorithm is O(M + N)
where M
is the length of your "translation list" and N
is the length of list a
.