【发布时间】:2019-12-23 06:05:17
【问题描述】:
我想根据 numpy 3d-array 中的值创建一个 numpy 2d-array,使用另一个 numpy 2d-array 来确定在轴 3 中使用哪个元素。
import numpy as np
#--------------------------------------------------------------------
arr_3d = np.arange(2*3*4).reshape(2,3,4)
print('arr_3d shape=', arr_3d.shape, '\n', arr_3d)
arr_2d = np.array(([3,2,0], [2,3,2]))
print('\n', 'arr_2d shape=', arr_2d.shape, '\n', arr_2d)
res_2d = arr_3d[:, :, 2]
print('\n','res_2d example using element 2 of each 3rd axis...\n', res_2d)
res_2d = arr_3d[:, :, 3]
print('\n','res_2d example using element 3 of each 3rd axis...\n', res_2d)
结果...
arr_3d shape= (2, 3, 4)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
arr_2d shape= (2, 3)
[[3 2 0]
[2 3 2]]
res_2d example using element 2 of each 3rd axis...
[[ 2 6 10]
[14 18 22]]
res_2d example using element 3 of each 3rd axis...
[[ 3 7 11]
[15 19 23]]
2 个示例结果显示了我使用轴 3 的第二个和第三个元素时得到的结果。但我想从 arr_3d 中获取由 arr_2d 指定的元素。所以...
- res_2d[0,0] would use the element 3 of arr_3d axis 3
- res_2d[0,1] would use the element 2 of arr_3d axis 3
- res_2d[0,2] would use the element 0 of arr_3d axis 3
etc
所以 res_2d 应该是这个样子...
[[3 6 8]
[14 19 22]]
我尝试使用这一行来获取 arr_2d 条目,但它会生成一个 4-dim 数组,我想要一个 2-dim 数组。
res_2d = arr_3d[:, :, arr_2d[:,:]]
【问题讨论】:
标签: python-3.x numpy indexing