Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NumPy replace values in matrix with np array

I have numpy array like:

x = np.array([
    ...
    [[0, 0, 0, 0],
     [0, 1, 1, 0],
     [0, 1, 1, 0],
     [0, 0, 0, 0]]
    ...
])

with shape (4800, 4, 4).

So i need to replace every 0 with [1, 1, 2] and every 1 with [5, 5, 9]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Result should be like this:

[[[1, 1, 2], [1, 1, 2], [1, 1, 2], [1, 1, 2]],
[[1, 1, 2], [5, 5, 9], [5, 5, 9], [1, 1, 2]],
[[1, 1, 2], [5, 5, 9], [5, 5, 9], [1, 1, 2]],
[[1, 1, 2], [1, 1, 2], [1, 1, 2], [1, 1, 2]]]

How do I do this?

>Solution :

Take advantage of the fact that you have 0 and 1, define a mapper array and index it:

                  #    0          1
mapper = np.array([[1, 1, 2], [5, 5, 9]])

out = mapper[a]

output:

array([[[[1, 1, 2],
         [1, 1, 2],
         [1, 1, 2],
         [1, 1, 2]],

        [[1, 1, 2],
         [5, 5, 9],
         [5, 5, 9],
         [1, 1, 2]],

        [[1, 1, 2],
         [5, 5, 9],
         [5, 5, 9],
         [1, 1, 2]],

        [[1, 1, 2],
         [1, 1, 2],
         [1, 1, 2],
         [1, 1, 2]]]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading