同样,在周期性条件下进行滚动或切片或切片的一种好且简单的方法是使用模数和 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]]])