2

I have a ndarray containing the dictionary keys arranged in a specific order. I want to create another ndarray containing the values of the respective keys. The order have to be maintained. Obvious approach is to iterate over the array containing the keys element by element but the problem is there is no way to know the shape of the array beforehand.

Is it possible to flatten the ndarray of keys and iterate over it to generate flat ndarray of values and finally unravel it without harming the order?

 mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
 input_pattern = np.array([['a', 'f'], ['b', 'e'], ['c', 'd']])
 expected_output = np.array([[1, 6], [2, 5], [3, 4]])

N. B. : In the above example pattern array is 2D, it may not be the case always. Also it may not contain all keys of the dictionary.

0

2 Answers 2

5

You can use np.vectorize with dict.get:

d = np.vectorize(mydict.get)

res = d(input_pattern)

print(res)

array([[1, 6],
       [2, 5],
       [3, 4]])
Sign up to request clarification or add additional context in comments.

1 Comment

This is amazing. Thank you.
0

the problem is there is no way to know the shape of the array beforehand.

We can try to use flat + list comprehension + reshape

np.array([mydict[v] for v in input_pattern.flat]).reshape(input_pattern.shape)

array([[1, 6],
       [2, 5],
       [3, 4]])

flat makes an 1-dimensional iterator out of the array and we later on use reshape to recover the shape of input_pattern.

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.