2014-06-20 73 views
1

索引中給定一個查找表numpy的陣列

colors = [ [0,0,0],\ 
      [0, 255, 0],\ 
      [0, 0, 255],\ 
      [255, 0, 0]] 

和索引numpy的矩陣輸入2×2:

a = np.array([[0,1],[1,1]]) 

我如何映射到一個2x2x3矩陣b,其中b[i][j] = colors[a[i][j]]?我想避免在這裏使用for循環。

回答

2

你試過:

colors[a] 

這裏有一個完整的例子:

import numpy as np 

colors = np.array([[0,0,0], 
        [0, 255, 0], 
        [0, 0, 255], 
        [255, 0, 0] 
        ]) 
a = np.array([[0, 1], [1, 1]]) 

new = colors[a] 
new.shape 
# (2, 2, 3) 
new 
# array([[[ 0, 0, 0], 
#   [ 0, 255, 0]], 
# 
#  [[ 0, 255, 0], 
#   [ 0, 255, 0]]]) 
+0

請注意,您在這裏重新定義顏色使用numpy的數組,否則你得到「OP顏色」的錯誤。 – agstudy

+0

@agstudy,非常真實。如果'colors'是列表列表,則只能使用切片或整數對其進行索引。 –