Manipulating array elements in NumPy

I have a given array 'a' like this:

import numpy as np

a = np.arange(-100.0, 110.0, 20.0, dtype=float) #increase 20
a = np.tile(a, 4)
a = a.reshape(4,11)

[[-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]
 [-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]
 [-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]
 [-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]]

      

From array 'a' I need to create a new array 'b' which looks like this:

[[ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]
 [ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]
 [ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]
 [ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]]

      

Actually, array "b":

b =  np.arange(100.0, -110.0, -20.0, dtype=float)
b = np.tile(b, 4)
b = b.reshape(4,11)

      

However, in my real problem the actual data is not fixed, only the index a ie, a [0,0] is fixed. So I have to create array "b" from array "a" by changing / modifying its elements using indices.

I tried to do the following, but couldn't imagine how to get the correct answer:

b = np.flipud(a)
print b

[[-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]
 [-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]
 [-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]
 [-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]]

b = np.rot90(a,1)
print b

[[ 100.  100.  100.  100.]
 [  80.   80.   80.   80.]
 [  60.   60.   60.   60.]
 [  40.   40.   40.   40.]
 [  20.   20.   20.   20.]
 [   0.    0.    0.    0.]
 [ -20.  -20.  -20.  -20.]
 [ -40.  -40.  -40.  -40.]
 [ -60.  -60.  -60.  -60.]
 [ -80.  -80.  -80.  -80.]
 [-100. -100. -100. -100.]]

      

What numeric functions are appropriate for this problem?

+3


source to share


1 answer


You can use np.fliplr

:

b = np.fliplr(a)
print b

[[ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]
 [ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]
 [ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]
 [ 100.   80.   60.   40.   20.    0.  -20.  -40.  -60.  -80. -100.]]

      

This function flips the array in the left / right direction.



The documentation also suggests the following equivalent slice operation:

a[:,::-1]

      

+2


source







All Articles