python - Python 中的循环切片

标签 python python-2.7 numpy slice

我在尝试将 Cesar Cipher 应用于每行具有不同移位值的矩阵时提出了这个问题,即给定矩阵 X

array([[1, 0, 8],
   [5, 1, 4],
   [2, 1, 1]])

对于 S = array([0, 1, 1]) 的移位值,输出需要是

array([[1, 0, 8],
   [1, 4, 5],
   [1, 1, 2]])

这很容易通过下面的代码实现:

Y = []
for i in range(X.shape[0]):
    if (S[i] > 0):
        Y.append( X[i,S[i]::].tolist() + X[i,:S[i]:].tolist() )
    else:
        Y.append(X[i,:].tolist())
Y = np.array(Y)

这是一个左循环移位。我想知道如何使用 numpy 数组以更有效的方式做到这一点?

更新:此示例将移位应用于矩阵的列。假设我们有一个 3D 数组

array([[[8, 1, 8],
        [8, 6, 2],
        [5, 3, 7]],

       [[4, 1, 0],
        [5, 9, 5],
        [5, 1, 7]],

       [[9, 8, 6],
        [5, 1, 0],
        [5, 5, 4]]])

然后,S = array([0, 0, 1]) 在列上的循环右移导致

array([[[8, 1, 7],
        [8, 6, 8],
        [5, 3, 2]],

       [[4, 1, 7],
        [5, 9, 0],
        [5, 1, 5]],

       [[9, 8, 4],
        [5, 1, 6],
        [5, 5, 0]]])

最佳答案

方法#1:使用modulus实现循环模式并获取新的列索引,然后简单地使用 advanced-indexing提取元素,给我们一个向量化的解决方案,就像这样 -

def cyclic_slice(X, S):
    m,n = X.shape
    idx = np.mod(np.arange(n) + S[:,None],n)
    return X[np.arange(m)[:,None], idx]

方法 #2: 我们还可以利用 strides 的力量进一步加速。这个想法是从开始连接切下的部分并将其附加到最后,然后创建长度与 cols 数量相同的滑动窗口,最后索引到适当的窗口编号以获得相同的翻转效果。实现就像这样-

def cyclic_slice_strided(X, S):
    X2 = np.column_stack((X,X[:,:-1]))
    s0,s1 = X2.strides
    strided = np.lib.stride_tricks.as_strided 

    m,n1 = X.shape
    n2 = X2.shape[1]
    X2_3D = strided(X2, shape=(m,n2-n1+1,n1), strides=(s0,s1,s1))
    return X2_3D[np.arange(len(S)),S]

sample 运行-

In [34]: X
Out[34]: 
array([[1, 0, 8],
       [5, 1, 4],
       [2, 1, 1]])

In [35]: S
Out[35]: array([0, 1, 1])

In [36]: cyclic_slice(X, S)
Out[36]: 
array([[1, 0, 8],
       [1, 4, 5],
       [1, 1, 2]])

运行时测试-

In [75]: X = np.random.rand(10000,100)
    ...: S = np.random.randint(0,100,(10000))

# @Moses Koledoye's soln
In [76]: %%timeit
    ...: Y = []
    ...: for i, x in zip(S, X):
    ...:     Y.append(np.roll(x, -i))
10 loops, best of 3: 108 ms per loop

In [77]: %timeit cyclic_slice(X, S)
100 loops, best of 3: 14.1 ms per loop

In [78]: %timeit cyclic_slice_strided(X, S)
100 loops, best of 3: 4.3 ms per loop

适应3D 案例

3D 情况调整方法 #1,我们将有 -

shift = 'left'
axis = 1 # axis along which S is to be used (axis=1 for rows)
n = X.shape[axis]
if shift == 'left':
    Sa = S
else:
    Sa = -S    

# For rows
idx = np.mod(np.arange(n)[:,None] + Sa,n)
out = X[:,idx, np.arange(len(S))]

# For columns
idx = np.mod(Sa[:,None] + np.arange(n),n)
out = X[:,np.arange(len(S))[:,None], idx]

# For axis=0
idx = np.mod(np.arange(n)[:,None] + Sa,n)
out = X[idx, np.arange(len(S))]

可能有一种方法可以为通用 提供通用解决方案,但我会保留到此为止。

关于python - Python 中的循环切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47963060/

相关文章:

python-3.x - Numba 在 np.astype 上无效使用 BoundFunction

python - 如何将逆向转置应用到 numpy 数组

python - OpenCV + Python + GigE 视觉相机

python - 为什么 str.format() 比 str() 更好?

python - Pyinstaller 错误 ImportError : No module named 'requests. packages.chardet.sys

python - 如何实现 "where"(numpy.where(...) )?

python - 有效地将字符串(或元组)转换为 ctypes 数组

python - python 中的插件管理器

python - 按字符串从列表中检索项目

python - 仅在 Django 中的 StreamingHttpResponse 中的模板上呈现当前状态