比循环更快的方法。 - 通过2D数组索引3D Numpy阵列
我有一个3D (3,2,3)
数组,而第一维( 3 )是灵活的,它可以是任何尺寸。
arr = np.array(
[[[56, 24, 32],
[56, 24, 32]],
[[51, 27, 72],
[51, 27, 72]],
[[36, 14, 49],
[36, 14, 49]]])
索引数组是(2,3)
:
idxs = np.array(
[[1, 0, 2],
[2, 1, 0]])
我想索引 arr by idxs 。预期的结果是:
[[[24 56 32]
[32 24 56]]
[[27 51 72]
[72 27 51]]
[[14 36 49]
[49 14 36]]])
如果我在下面的循环中使用循环需要很多时间:
for i, arr2d in enumerate(arr):
for j, (arr1d, idx) in enumerate(zip(arr2d, idxs)):
arr[i, j] = arr1d[idx]
所以我的问题是: 我如何加快此过程?
I have a 3d (3, 2, 3)
array and first dimension(3) is flexible it can be any size.
arr = np.array(
[[[56, 24, 32],
[56, 24, 32]],
[[51, 27, 72],
[51, 27, 72]],
[[36, 14, 49],
[36, 14, 49]]])
Indexing array is (2,3)
:
idxs = np.array(
[[1, 0, 2],
[2, 1, 0]])
I wanna index arr by idxs. Expected result is :
[[[24 56 32]
[32 24 56]]
[[27 51 72]
[72 27 51]]
[[14 36 49]
[49 14 36]]])
If i use for loop like below it takes a lot of time :
for i, arr2d in enumerate(arr):
for j, (arr1d, idx) in enumerate(zip(arr2d, idxs)):
arr[i, j] = arr1d[idx]
So my question is : How can i speed up this process ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

使用
np.take_along_axis
Use
np.take_along_axis