# 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]])
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)
2条答案
按热度按时间wf82jlnq1#
是的,这可以用高级索引来完成。而且你不需要任何循环。
brtdzjyr2#
是的,NumPy中有一个名为np.roll()的函数,可以用来实现所需的结果。下面是如何使用它的示例: