您的mode 的pad 的核心是:
newmat = narray.copy()
# API preserved, but completely new algorithm which pads by building the
# entire block to pad before/after `arr` with in one step, for each axis.
if mode == 'constant':
for axis, ((pad_before, pad_after), (before_val, after_val)) \
in enumerate(zip(pad_width, kwargs['constant_values'])):
newmat = _prepend_const(newmat, pad_before, before_val, axis)
newmat = _append_const(newmat, pad_after, after_val, axis)
所以是 pad_width 元组(元组中的)决定了操作,无论是前置还是附加常量填充。请注意,它在轴上进行迭代。
您自己的代码可能会同样快,因为 pad 在这里没有做任何神奇的事情(或编译)。
prepend 函数执行如下连接:
np.concatenate((np.zeros(padshape, dtype=arr.dtype), arr),
axis=axis)
详情请见np.lib.arraypad.py。
因此,对于每个非零填充量,它都会连接到所需形状的零块上。
In [280]: x = np.array([[1, 2, 3],[4, 5, 6]])
您的两个pad 版本:
In [281]: np.pad(x,((0,0),(1,0)), mode='constant')[:, :-1]
Out[281]:
array([[0, 1, 2],
[0, 4, 5]])
In [282]: np.pad(x,((0,0),(0,1)), mode='constant')[:, 1:]
Out[282]:
array([[2, 3, 0],
[5, 6, 0]])
直接insert 等价物:
In [283]: res = np.zeros_like(x)
In [284]: res[:,1:] = x[:,:-1]
In [285]: res
Out[285]:
array([[0, 1, 2],
[0, 4, 5]])
In [286]: res = np.zeros_like(x)
In [287]: res[:,:-1] = x[:,1:]
In [288]: res
Out[288]:
array([[2, 3, 0],
[5, 6, 0]])
你可以在第一个轴上做同样的事情。一般表达式为
res = np.zeros_like(x)
idx1 = (slice(...), slice(...))
idx2 = (slice(...), slice(...))
res[idx1] = x[idx2]
idx 元组取决于滚动轴和方向。
例如
idx1 = (slice(None), slice(1,None))
idx2 = (slice(None), slice(None,-1))
2轴2方向,即4对。