独立滚动矩阵的行

2024-05-18

我有一个矩阵(准确地说,是 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]]

# Always use a negative shift, so that column_indices are valid.
# Alternative: r %= A.shape[1]
r[r < 0] += A.shape[1]
column_indices = column_indices - r[:, np.newaxis]

result = A[rows, column_indices]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

独立滚动矩阵的行 的相关文章

随机推荐