0

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]

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?

2 Answers 2

3

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]]]])
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a new array and assign the values according to the value in the old one.

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

x_new = np.zeros((*(x.shape), 3))
x_new[x==0] = [1, 1, 2]
x_new[x==1] = [5, 5, 9]

print(x_new)

This results in the following output:

[[[[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.]]]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.