[SciPy-User] unexpected behavior when reverting twice ([::-1, 0])

Robert Kern robert.kern at gmail.com
Mon May 9 15:27:47 EDT 2011


On Mon, May 9, 2011 at 14:13, Bastian Weber
<bastian.weber at gmx-topmail.de> wrote:
> Hello,
>
> I found an unexpected behavior when reverting an array and then
> reverting a part of it again (numpy version 1.3.0):
>
>
> In [1]: import numpy as np
>
> In [2]: a = np.arange(5)
>
> In [3]: a
> Out[3]: array([0, 1, 2, 3, 4])
>
> In [4]: b = np.c_[a, a*3]
>
> In [5]: b
> Out[5]:
> array([[ 0,  0],
>        [ 1,  3],
>        [ 2,  6],
>        [ 3,  9],
>        [ 4, 12]])
>
> In [6]: c = b[::-1, :]
>
> In [7]: c
> Out[7]:
> array([[ 4, 12],
>        [ 3,  9],
>        [ 2,  6],
>        [ 1,  3],
>        [ 0,  0]])
>
> In [8]: c[:,0] = c[::-1, 0]
>
> In [9]: c
> Out[9]:
> array([[ 0, 12],
>        [ 1,  9],
>        [ 2,  6],
>        [ 1,  3],
>        [ 0,  0]])
>
> In [10]: b
> Out[10]:
> array([[ 0,  0],
>        [ 1,  3],
>        [ 2,  6],
>        [ 1,  9],
>        [ 0, 12]])
>
>
> I would have expected the first column of c to be [0,1,2,3,4] an b to be
> the same as in step 5.

c[::-1,0] makes a view on c, not a copy. When you assign back into
c[:,0], you end up modifying the elements near the end of c[::-1,0]
(i.e. near the beginning of c[:,0]).

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the SciPy-User mailing list