Reputation: 33
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?
Upvotes: 3
Views: 134
Reputation: 176750
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]
Upvotes: 2