python - Shifting 3D numpy array -
i able shift 3d numpy array in either direction along height axis. if positive shift of 3 given, values in array shift , 3 new slices of zeros appear @ bottom of array. opposite occur if negative shift given, slices shift down along height axis , new slices of zeros appear @ top.
i have attempted reshaping array 1d , shifting left , right, , returning 3d. however, shifts array along wrong direction. tried implementing numpy.rollaxis before reshaping, shifting along correct axis. system i'm working on not recognize numpy functions , not perform rollaxis.
thanks!
your question little ill defined. first, 'height' axis not clear definition of 1 after in 3d array. better locate them position in shape tuple. going take meaning 'along first axis', should obvious how different one.
second, while clear want zeros fill in shifted data, don't specify want data on other side: should disappear beyond array's boundary , lost? or should array extended keep all?
for former, numpy has roll
function, similar want, instead of filling in zeros, copies data other side of array. can replace zeros afterwards:
>>> = np.arange(60).reshape(3, 4, 5) >>> 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]]])
had shift been negative, instead of b[:shift, :, :] = 0
go b[-shift:, :, :] = 0
.
if don't want lose data, adding slices of zeros @ top or bottom of array. first 3 dimensions, numpy has vstack
, hstack
, , dstack
, , vstack
should 1 after:
>>> = 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]]])
if wanted zeros appended @ bottom, change order of parameters in call stacking function.
Comments
Post a Comment