2

I have a numpy array that is built with coded sections. The sections come in 2x2 blocks. I have a large dictionary of what those 2x2 blocks should be replaced with. How do I replace those 2x2 codes with values in the dictionary.

info_dict = {
    5: np.array([[1, 0], [1, 0]], "int"),
    6: np.array([[1, 0], [0, 1]], "int"),
    7: np.array([[0, 1], [1, 0]], "int"),
    8: np.array([[1, 1], [0, 0]], "int"),
}
print(np.array([[5, 5, 8, 8], [5, 5, 8, 8], [6, 6, 7, 7], [6, 6, 7, 7]]))
print(np.array([[1, 0, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]]))
# before (coded)
[[5 5 8 8]
 [5 5 8 8]
 [6 6 7 7]
 [6 6 7 7]]
# after (final matrix)
[[1 0 1 1]
 [1 0 0 0]
 [1 0 0 1]
 [0 1 1 0]]

For reference

#5
[[1 0]
 [1 0]]
#6
[[1 0]
 [0 1]]
#7
[[0 1]
 [1 0]]
#8
[[1 1]
 [0 0]]
1
  • Where is the data coming from. Are you open to changing the format? Commented Dec 21, 2021 at 23:48

2 Answers 2

1

One way to do it:

import numpy as np

info_dict = {
    5: np.array([[1, 0], [1, 0]], "int"),
    6: np.array([[1, 0], [0, 1]], "int"),
    7: np.array([[0, 1], [1, 0]], "int"),
    8: np.array([[1, 1], [0, 0]], "int"),
}

a = np.array([[5, 5, 8, 8], [5, 5, 8, 8], [6, 6, 7, 7], [6, 6, 7, 7]])
np.block([[info_dict[b] for b in r] for r in a[::2, ::2]])

It gives:

[[1 0 1 1]
 [1 0 0 0]
 [1 0 0 1]
 [0 1 1 0]]
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming your dictionary has a small number of integers in it, and your squares are N to a side, you info_dict as follows:

mapping = np.zeros((max(info_dict) + 1, N, N), dtype=int)
for channel, value in info_dict.items():
    mapping[channel] = value

If you can store the dictionary in this format to begin with, that's even better. Now you can use simple index with some rearrangement to get the result:

after = mapping[before[::N, ::N]].transpose(0, 2, 1, 3).reshape(before.shape)

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.