gpt4 book ai didi

python - 独立移动 numpy 数组的行

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:00 31 4
gpt4 key购买 nike

这是问题的扩展 here (引述如下)

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

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

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?

公认的解决方案是:

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]

我基本上想做同样的事情,除了当索引滚动“超过”行的末尾时,我希望用 NaN 填充行的另一侧,而不是将值移动到周期性地排在行的“前面”。

也许以某种方式使用 np.pad?但我不知道如何让它以不同的数量填充不同的行。

最佳答案

灵感来自 Roll rows of a matrix independently's solution , 这是一个基于 np.lib.stride_tricks.as_strided 的矢量化的-

from skimage.util.shape import view_as_windows as viewW

def strided_indexing_roll(a, r):
# Concatenate with sliced to cover all rolls
p = np.full((a.shape[0],a.shape[1]-1),np.nan)
a_ext = np.concatenate((p,a,p),axis=1)

# Get sliding windows; use advanced-indexing to select appropriate ones
n = a.shape[1]
return viewW(a_ext,(1,n))[np.arange(len(r)), -r + (n-1),0]

sample 运行-

In [76]: a
Out[76]:
array([[4, 0, 0],
[1, 2, 3],
[0, 0, 5]])

In [77]: r
Out[77]: array([ 2, 0, -1])

In [78]: strided_indexing_roll(a, r)
Out[78]:
array([[nan, nan, 4.],
[ 1., 2., 3.],
[ 0., 5., nan]])

关于python - 独立移动 numpy 数组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51200369/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com