相关疑难解决方法(0)

独立移动 numpy 数组的行

这是这里提出的问题的扩展(引用如下)

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

A = np.array([[4, 0, 0],
              [1, 2, 3],
              [0, 0, 5]])
Run Code Online (Sandbox Code Playgroud)

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

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]]
Run Code Online (Sandbox Code Playgroud)

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

接受的解决方案是:

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)

python arrays numpy

5
推荐指数
1
解决办法
3934
查看次数

标签 统计

arrays ×1

numpy ×1

python ×1