我有一个矩阵(准确地说是 2d numpy ndarray):
A = np.array([[4, 0, 0],
[1, 2, 3],
[0, 0, 5]])
我想根据另一个数组中的滚动值独立滚动 A
的每一行:
r = np.array([2, 0, -1])
也就是说,我想这样做:
print np.array([np.roll(row, x) for row,x in zip(A, r)])
[[0 0 4]
[1 2 3]
[0 5 0]]
有没有办法有效地做到这一点?也许使用花哨的索引技巧?
最佳答案
当然你可以使用高级索引来做到这一点,它是否是最快的方法可能取决于你的数组大小(如果你的行很大,它可能不是):
rows, column_indices = np.ogrid[:A.shape[0], :A.shape[1]]
# Use always a negative shift, so that column_indices are valid.
# (could also use module operation)
r[r < 0] += A.shape[1]
column_indices = column_indices - r[:, np.newaxis]
result = A[rows, column_indices]
关于python - 独立滚动矩阵的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20360675/