Home > Back-end >  Python Numpy: How to reverse a slice operation?
Python Numpy: How to reverse a slice operation?

Time:09-25

I'd like to 'reverse' a slice operation. For example, the original array is:

import numpy as np
a=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

>>> array([[ 1,  2,  3,  4],
           [ 5,  6,  7,  8],
           [ 9, 10, 11, 12]])

Then, I slice this array, and do some operations on it (times 2):

b = 2 * a[::-1,::2]

>>> array([[18, 22],
           [10, 14],
           [ 2,  6]])

How can I put all elements in b back to their original position in a (Note axis 0 is flipped), i.e. the final result should be:

>>> array([[ 2,  0,  6,  0],
           [10,  0, 14,  0],
           [18,  0, 22,  0]])

I figured something like as_strided and flip should be used, but I can't seem to get it working. Thanks for any help!!

CodePudding user response:

import numpy as np
a=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
req_array = np.zeros(a.shape)
req_array[::-1,::2] = 2 * a[::-1,::2]
print(req_array) ## your required array

CodePudding user response:

You could just np.zeros(shape=(3,4)), index them, but you would need to reverse[::-1] before doing so. Seems like a lot of pain for something that can be solved with just as simple as saving the array before under a different variable, as you always going to have to save the shape anyway. e.g.

var1 = beforeArray
var2 = 2 * var1 [::-1,::2]
to_reverse_var2 = np.zeros(var1.shape)
then index

But would be much easier to just save the var instead, because you will always need the array.shape anyway. Just use self. or global if it is functional problem.

Other ideas would be play about with matrix methods outside of numpy to speed up process such as.

  • Related