Last active
August 27, 2024 08:52
-
-
Save hotohoto/52ddf3743911d5bb3167dd56d828b694 to your computer and use it in GitHub Desktop.
How to use `np.vectorize()` when mapping between different dimensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# reduce dimension | |
mapping1 = { | |
(1, 2): 0, | |
(3, 4): 1, | |
(5, 6): 2, | |
} | |
def mapper1(m1, m2): | |
return mapping1.get((m1, m2)) | |
a = np.array([[1, 2], [3, 4], [5, 6]]) | |
b = np.vectorize(mapper1)(a[:, 0], a[:, 1]) | |
print(b) | |
# extend dimension | |
mapping2 = { | |
0: [1, 2], | |
1: [3, 4], | |
2: [5, 6], | |
} | |
a = np.array([0, 1, 2]) | |
b = np.array(np.vectorize(mapping2.get, otypes=[list])(a).tolist()) | |
print(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment