问题
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.
回答1:
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]])
回答2:
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
.
来源:https://stackoverflow.com/questions/51800651/constructing-a-ndarray-of-values-from-another-ndarray-containing-dictionary-keys