这是这里提出的问题的扩展(引用如下)
我有一个矩阵(准确地说是二维 numpy ndarray):
Run Code Online (Sandbox Code Playgroud)A = np.array([[4, 0, 0], [1, 2, 3], [0, 0, 5]])我想根据另一个数组中的滚动值独立滚动 A 的每一行:
Run Code Online (Sandbox Code Playgroud)r = np.array([2, 0, -1])也就是说,我想这样做:
Run Code Online (Sandbox Code Playgroud)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, …Run Code Online (Sandbox Code Playgroud)