如何在numpy中将2d数组移位1d数组?3d乘以2d也是一样

uyto3xhc  于 2023-04-12  发布在  其他
关注(0)|答案(2)|浏览(156)

假设我有一个2d数组和一个1d数组,如下所示:

a= np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])
b= np.array([0,2,1,0])

结果我想要这个:

out= np.array([[1,2,3,1],[2,3,1,2],[3,1,2,3]])

a中的每个值都沿着轴移动另一个数组中的值。
在numpy或其他常用库中有类似的东西吗?我需要在3d中对一个大数组(~ 10000,10000,100)这样做,所以通过迭代来做感觉是错误的。

wf82jlnq

wf82jlnq1#

是的,这可以用高级索引来完成。而且你不需要任何循环。

# Get the row and col indices of the ndarray
rowidx, colidx = np.ogrid[:a.shape[0], :a.shape[1]]
# update row idices
updt_rowidx = rowidx - b
# Use the updated indices
a[updt_rowidx, colidx]
>> array([[1, 2, 3, 1],
       [2, 3, 1, 2],
       [3, 1, 2, 3]])
brtdzjyr

brtdzjyr2#

是的,NumPy中有一个名为np.roll()的函数,可以用来实现所需的结果。下面是如何使用它的示例:

import numpy as np

a = np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])
b = np.array([0,2,1,0])

out = np.empty_like(a)

for i, shift in enumerate(b):
    out[i] = np.roll(a[i], shift)

print(out)

相关问题