如何用numpy进行数组查找/替换?

时间:2011-11-18 20:30:14

标签: python numpy

我有一个2D numpy数组,A包含另一个数组B的索引。 使用numpy从CA获取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]])

2 个答案:

答案 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]]