Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   numpy array operation (http://www.velocityreviews.com/forums/t957040-numpy-array-operation.html)

C. Ng 01-29-2013 08:41 AM

numpy array operation
 
Is there a numpy operation that does the following to the array?

1 2 ==> 4 3
3 4 2 1

Thanks in advance.



Peter Otten 01-29-2013 09:28 AM

Re: numpy array operation
 
C. Ng wrote:

> Is there a numpy operation that does the following to the array?
>
> 1 2 ==> 4 3
> 3 4 2 1


How about

>>> a

array([[1, 2],
[3, 4]])
>>> a[::-1].transpose()[::-1].transpose()

array([[4, 3],
[2, 1]])

Or did you mean

>>> a.reshape((4,))[::-1].reshape((2,2))

array([[4, 3],
[2, 1]])

Or even

>>> -a + 5

array([[4, 3],
[2, 1]])



Tim Williams 01-29-2013 12:59 PM

Re: numpy array operation
 
On Tuesday, January 29, 2013 3:41:54 AM UTC-5, C. Ng wrote:
> Is there a numpy operation that does the following to the array?
>
>
>
> 1 2 ==> 4 3
>
> 3 4 2 1
>
>
>
> Thanks in advance.


>>> import numpy as np
>>> a=np.array([[1,2],[3,4]])
>>> a

array([[1, 2],
[3, 4]])
>>> np.fliplr(np.flipud(a))

array([[4, 3],
[2, 1]])


Terry Reedy 01-29-2013 08:05 PM

Re: numpy array operation
 
On 1/29/2013 1:49 PM, Alok Singhal wrote:
> On Tue, 29 Jan 2013 00:41:54 -0800, C. Ng wrote:
>
>> Is there a numpy operation that does the following to the array?
>>
>> 1 2 ==> 4 3
>> 3 4 2 1
>>
>> Thanks in advance.

>
> How about:
>
>>>> import numpy as np
>>>> a = np.array([[1,2],[3,4]])
>>>> a

> array([[1, 2], [3, 4]])
>>>> a[::-1, ::-1]

> array([[4, 3], [2, 1]])
>


Nice. The regular Python equivalent is

a = [[1,2],[3,4]]
print([row[::-1] for row in a[::-1]])
>>>

[[4, 3], [2, 1]]

The second slice can be replaced with reversed(a), which returns an
iterator, to get
[row[::-1] for row in reversed(a)]
The first slice would have to be list(reversed(a)) to get the same result.

--
Terry Jan Reedy



All times are GMT. The time now is 02:37 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.