从另一个包含字典键的 ndarray 构造值的 ndarray

Constructing a ndarray of values from another ndarray containing dictionary keys

我有一个包含按特定顺序排列的字典键的 ndarray。我想创建另一个包含各个键值的 ndarray。必须维持秩序。 显而易见的方法是逐个元素地遍历包含键的数组,但问题是无法事先知道数组的形状。

是否可以展平 ndarray 的键并对其进行迭代以生成扁平的 ndarray 的值并最终在不损害顺序的情况下解开它?

 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. :在上面的例子中,模式数组是二维的,但不一定总是这样。它也可能不包含字典的所有键。

您可以将 np.vectorizedict.get 一起使用:

d = np.vectorize(mydict.get)

res = d(input_pattern)

print(res)

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

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

我们可以尝试使用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 恢复 input_pattern.

的形状