我有一个2D numpy数组,A
包含另一个数组B
的索引。 使用numpy从C
和A
获取B
的好方法是什么?
A = array([[1, 1, 0, 2],
[1, 0, 0, 2],
[1, 1, 0, 2]])
B = array([0, 5, 3])
C = array([[5, 5, 0, 3],
[5, 0, 0, 3],
[5, 5, 0, 3]])
答案 0 :(得分:9)
这个C = B[A]
怎么样?这就是numpy的美丽:
In [1]: import numpy as np
In [2]: A = np.array([[1, 1, 0, 2],
...: [1, 0, 0, 2],
...: [1, 1, 0, 2]])
In [3]: B = np.array([0, 5, 3])
In [4]: B[A]
Out[4]:
array([[5, 5, 0, 3],
[5, 0, 0, 3],
[5, 5, 0, 3]])
答案 1 :(得分:-1)
x,y = a.shape
for i in range(x):
for j in range(y)
c[i][j] = b[a[i][j]]