1

I would like to be able to shift a 3D numpy array in either direction along the height axis. If a positive shift of a say 3 is given, all values in the array shift up and 3 new slices of zeros appear at the bottom of the array. The opposite would occur if a negative shift is given, all slices shift down along the height axis and new slices of zeros appear at the top.

I have attempted reshaping the array to 1D and shifting left and right, and then returning to 3D. However, this shifts the array along the wrong direction. I tried implementing numpy.rollaxis before reshaping, thus shifting along the correct axis. But the system I'm working on does not recognize all numpy functions and will not perform rollaxis.

Thanks!

4

1 回答 1

4

你的问题有点不明确。首先,“高度”轴对于您在 3D 阵列中所追求的不是一个非常明确的定义。最好通过形状元组中的位置来定位它们。我将把它理解为“沿着第一个轴”,但是对于不同的轴应该如何做到这一点应该很明显。

其次,虽然很明显您希望零来填充移位的数据,但您没有指定要对另一侧的数据做什么:它应该消失在数组边界之外并丢失吗?还是应该扩展数组以保留所有内容?

对于前者,numpy 具有与roll您想要的功能类似的功能,但它不是用零填充,而是从数组的另一侧复制数据。之后您可以简单地用零替换它:

>>> a = np.arange(60).reshape(3, 4, 5)
>>> a
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]],

       [[40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49],
        [50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59]]])
>>> b = np.roll(a, 2, axis=0)
>>> b[:2,:, :] = 0
>>> b
array([[[ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0]],

       [[ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0]],

       [[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]]])

如果转变是负面的,而不是b[:shift, :, :] = 0你会去b[-shift:, :, :] = 0

如果您不想丢失数据,那么您基本上只是在数组的顶部或底部添加零片。对于前三个维度,numpy 有vstack, hstack, 和dstack, 并且vstack应该是您所追求的:

>>> a = np.arange(60).reshape(3, 4, 5)
>>> b = np.vstack((np.zeros((2,)+a.shape[1:], dtype=a.dtype), a))
>>> b
array([[[ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0]],

       [[ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0]],

       [[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]],

       [[40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49],
        [50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59]]])

如果您希望在底部附加零,只需更改调用堆栈函数中的参数顺序即可。

于 2013-04-09T14:58:10.823 回答