独立滚动矩阵行 [英] Roll rows of a matrix independently

查看:77
本文介绍了独立滚动矩阵行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵(准确地说是2d numpy ndarray):

I have a matrix (2d numpy ndarray, to be precise):

A = np.array([[4, 0, 0],
              [1, 2, 3],
              [0, 0, 5]])

我想根据另一个数组中的滚动值独立滚动A的每一行:

And I want to roll each row of A independently, according to roll values in another array:

r = np.array([2, 0, -1])

也就是说,我要这样做:

That is, I want to do this:

print np.array([np.roll(row, x) for row,x in zip(A, r)])

[[0 0 4]
 [1 2 3]
 [0 5 0]]

有没有办法有效地做到这一点?也许使用花哨的索引技巧?

Is there a way to do this efficiently? Perhaps using fancy indexing tricks?

推荐答案

您当然可以使用高级索引来完成此操作,是否最快的方法可能取决于您的数组大小(如果行很大,则可能不是):

Sure you can do it using advanced indexing, whether it is the fastest way probably depends on your array size (if your rows are large it may not be):

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]

这篇关于独立滚动矩阵行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆