python - 独立滚动矩阵的行

标签 python performance numpy

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

相关文章:

python - 在 BOINC 上运行 Python 应用程序

python - 解析异常中的错误行号

Java 执行时间受字符串格式影响吗?

iOS 上的 CSS 过渡性能

python - 如何在 numba 中使用 numpy 函数

python - 将 numpy 数组 block 转换为元组

python - 如何在 numpy ndArray 中插入值?

python - 如何从列表中的键获取字典值?

python - 如何检查函数/方法采用哪些参数?

ruby-on-rails - 将 YAML 文件作为常量加载到 Rails Controller 中是否有效?