Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace specific values within 2D array [closed]

I have a large 2D array, array, with each entry being a large array of numbers:

array = [
            [1, 0, 3, ...],
            [5, 4, 1, ...],
            [1, 2, 3, ...],
            ...
        ]

All the numbers in the 2D array are from 0-5 and I have to somehow find and replace specific numbers, like, for example, all occurrences of the number 3 and replace it with 5.

like image 805
ssal Avatar asked Jun 28 '26 04:06

ssal


1 Answers

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!

like image 153
jojo Avatar answered Jun 30 '26 17:06

jojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!