问题描述
我有一个ndarray,其中包含按特定顺序排列的字典键。我想创建另一个包含各个键值的ndarray。必须保持顺序。
显而易见的方法是逐个元素地迭代包含键的数组,但是问题是无法事先知道数组的形状。
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.
是否可以展平键的ndarray并对其进行迭代以生成平坦的ndarray值,并最终在不损害顺序的情况下对其进行拆散?
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.:在上面的示例中,图案数组是2D的,并非总是如此。另外,它可能不包含字典的所有键。
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.
推荐答案
您可以使用与 dict.get
:
d = np.vectorize(mydict.get)
res = d(input_pattern)
print(res)
array([[1, 6],
[2, 5],
[3, 4]])
这篇关于从另一个包含字典键的ndarray构造值的ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!