3

I have a given array 'a' as follows:

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 make new array 'b' which looks as follows:

[[ 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' is:

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 are not fixed, only the index of a i.e., a[0,0] is fixed. Therefore, I have to produce the array 'b' from array 'a' by reshaping/rearranging its elements using indices.

I tried as follows, but could not 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 numpy functions are suitable for this problem?

1 Answer 1

2

You could 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 a left/right direction.

The documentation also suggests the following equivalent slice operation:

a[:,::-1]
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks +1, sorry I did not used np.fliplr
Sorry waiting for 15 reputation for +1.
No problem - glad the answer was helpful!
Glad to be able to +1 finally!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.