python - 基于 2D 选择数组(带有索引值)选择 3D 数组中的值
问题描述
我有一个 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]]
3D 数组 (4,2,3) 用之前的 2D 选择掩码过滤-
[[[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]]
解决方案
编辑:忽略线上。 从 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)
推荐阅读
- python - 在 django 中设置相对于用户的时区
- terraform - 使用 Scaleway 的 Terraform 不支持的属性错误
- .net - 使用 ansi 转义序列让 dotnet 输出
- angular - 类型“IComponent”上不存在属性“reduce”
- c# - 从问卷样式DataGridView的多个复选框列中仅选择一个复选框
- c# - 创建多个y轴图表epplus c#
- java - 从列表中获取数据
并将其放入 String 对象 - php - PHP 警告:PHP 启动:无法加载动态库 'php_fileinfo.dll'
- java - Java jjwt 使用 HSM 或 vault 将令牌的签名外部化
- angular - 从 Angular UI 导航 URL 中删除 X-Powered-By:express 响应标头