基于2D选择数组(具有索引值)选择3D数组中的值

时间:2018-06-13 14:03:21

标签: python arrays indexing mask

我有一个2D选择或掩码数组,其形状(375,297)在每个单元格中都有一个对应于索引整数的值,范围从0到23.我想使用这个2D数组来选择3D阵列(具有形状(24,375,297))来自第一维(具有长度24的那个)的单元格,以便输出具有形状(375,297)的2D阵列。我一直在尝试使用花哨的索引和xarray包而没有成功。如何使用python 3.6做到这一点?

小例子:

2D选择数组或掩码(2,3),其值(3d数组的索引)范围为0到3 -

[[0,1,2],
 [3,1,0]] 

使用先前的2D选择蒙版 -

过滤的3D阵列(4,2,3)
[[[25,27,30],
  [15,18,21]],
 [[13,19, 1],
  [5, 7, 10]],
 [[10, 1, 2],
  [5, 6, 18]],
 [[3, 13,18],
  [30,42,24]]]

应用2D选择蒙版后的预期2D(2,3)阵列输出 -

[[25,19, 2],
 [30, 7,21]]

1 个答案:

答案 0 :(得分:0)

编辑:忽略该行。 从2D数组中获取所需数组的索引,然后只从3D数组中获取该索引。

index3d = arr2d[i][j]
new_arr = arr3d[index3d]    # gives the 2D array at the 3D array's index 'index3d'

示例:

# shape of arr3d = 3,2,3
arr3d = [[[2,4,6],[8,10,12]],[[3,6,9],[12,15,18]],[[1,6,2],[5,3,4]]]
# shape of arr2d = 2,3, values 0-2
arr2d = [[0,1,0],[2,1,2]]
# select arr3d index from arr2d
index3d = arr2d[1][0]
# get 2D array from arr3d at index3d
new_arr = arr3d[index3d]
# prints:
# [[1, 6, 2], [5, 3, 4]]
print(new_arr)

编辑:

# shape of arr3d = 3,2,3
arr3d = [[[2,4,6],[8,10,12]],
         [[3,6,9],[12,15,18]],
         [[1,6,2],[5,3,4]]]
# shape of arr2d = 2,3, values 0-2
arr2d = [[0,1,0],
         [2,1,2]]
new_arr = [[],[]]
# append the values from the correct 2D array in arr3d
for row in range(len(arr2d)):
    for col in range(len(arr2d[row])):
        i = arr2d[row][col] # i selects the correct 2D array from arr3d
        new_arr[row].append(arr3d[i][row][col]) # get the same row/column from the new array
# prints:
# [[2, 6, 6], [5, 15, 4]]
print(new_arr)
相关问题