问题
I have a 2D selection or mask array, with shape (375, 297) that has in each cell a value that corresponds to an index integer number, ranging from 0 to 23. I’d like to use this 2D array to select in a 3D array (with shape (24, 375, 297)) the cells from the first dimension (the one with length 24) so to output a 2D array with shape (375,297). I've been trying with fancy indexing and xarray package without success. How to do that using python 3.6?
Small example:
2D selection array or mask (2,3), with values (indices for 3d array) ranging from 0 to 3 -
[[0,1,2],
[3,1,0]]
3D array (4,2,3) to be filtered with the previous 2D selection mask-
[[[25,27,30],
[15,18,21]],
[[13,19, 1],
[5, 7, 10]],
[[10, 1, 2],
[5, 6, 18]],
[[3, 13,18],
[30,42,24]]]
Expected 2D (2,3) array Output after applying the 2D selection mask -
[[25,19, 2],
[30, 7,21]]
回答1:
Edit: Ignore above the line. Get the index of the array you want from your 2D array, then simply get that index alone from the 3D array.
index3d = arr2d[i][j]
new_arr = arr3d[index3d] # gives the 2D array at the 3D array's index 'index3d'
Example:
# 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)
Edit:
# 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)
来源:https://stackoverflow.com/questions/50839212/select-values-in-3d-array-based-on-a-2d-selection-array-with-indices-values