numpy - 在周期性条件下切片numpy数组

标签 numpy python-2.7

如何在周期性条件下切片 3x3 形状的 numpy 数组。

例如,为简单起见,它在一维中:

import numpy as np
a = np.array(range(10))

如果切片在数组的长度内,则很简单
sub = a[2:8]

结果是 array([2, 3, 4, 5, 6, 7]) .现在,如果我需要从 7 切片到 5...
sub = a[7:5]

结果显然是array([], dtype=int32) .但我需要的是array([7,8,9,0,1,2,3,4])
有没有什么有效的方法可以做到这一点?

最佳答案

同样,在周期性条件下进行滚动或切片或切片的一种简单好方法是使用模数和 numpy.reshape。
例如

import numpy as np
a = np.random.random((3,3,3))
array([[[ 0.98869832,  0.56508155,  0.05431135],
        [ 0.59721238,  0.62269635,  0.78196073],
        [ 0.03046364,  0.25689747,  0.85072087]],

       [[ 0.63096169,  0.66061845,  0.88362948],
        [ 0.66854665,  0.02621923,  0.41399149],
        [ 0.72104873,  0.45633403,  0.81190428]],

       [[ 0.42368236,  0.11258298,  0.27987449],
        [ 0.65115635,  0.42433058,  0.051015  ],
        [ 0.60465148,  0.12601221,  0.46014229]]])

假设我们需要对 [0:3, -1:1, 0:3] 进行切片,其中 3:1 是一个滚动切片。
a[0:3, -1:1, 0:3]
array([], shape=(3, 0, 3), dtype=float64)

这是很正常的。解决办法是:
sl0 = np.array(range(0,3)).reshape(-1,1, 1)%a.shape[0]
sl1 = np.array(range(-1,1)).reshape(1,-1, 1)%a.shape[1]
sl2 = np.array(range(0,3)).reshape(1,1,-1)%a.shape[2]

a[sl0,sl1,sl2]
array([[[ 0.03046364,  0.25689747,  0.85072087],
        [ 0.98869832,  0.56508155,  0.05431135]],

       [[ 0.72104873,  0.45633403,  0.81190428],
        [ 0.63096169,  0.66061845,  0.88362948]],

       [[ 0.60465148,  0.12601221,  0.46014229],
        [ 0.42368236,  0.11258298,  0.27987449]]])

关于numpy - 在周期性条件下切片numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15113181/

相关文章:

python - 使用多个 bin numpy 直方图拆分一个值

numpy - 有没有办法在 NumPy 中获取矩阵的 sqrt?不是元素明智的,而是作为一个整体

python - Odoo报告错误: Qweb error maximum recursion depth exceeded

python - 在 Mac 11.0.1 上运行 Django 站点时出现 AttributeError

python - 将字典的内容导出到 m x n 矩阵

python - Numpy 形状相同,均值返回不同的形状

python - 使用 numpy 将整数拆分为数字

python - "Linking"或在 Python 中转发子记录器

python - scikit-learn中决策树中的AUC计算

python - 使用 matplotlib 创建热图