numpy slice: create view, not copy

Travis Oliphant oliphant.travis at ieee.org
Thu Oct 12 19:03:05 EDT 2006


K. Jansma wrote:
> Hi,
> 
> given an array:
> 
> import numpy
> a = numpy.arange(100).reshape((10,10))
> print a
> 
> [[ 0  1  2  3  4  5  6  7  8  9]
>  [10 11 12 13 14 15 16 17 18 19]
>  [20 21 22 23 24 25 26 27 28 29]
>  [30 31 32 33 34 35 36 37 38 39]
>  [40 41 42 43 44 45 46 47 48 49]
>  [50 51 52 53 54 55 56 57 58 59]
>  [60 61 62 63 64 65 66 67 68 69]
>  [70 71 72 73 74 75 76 77 78 79]
>  [80 81 82 83 84 85 86 87 88 89]
>  [90 91 92 93 94 95 96 97 98 99]]
> 
> 
> I'd like to create a new array that is a view of a, i.e. it shares data. If
> a is updated, this new array should be automatically 'updated'.
> 
> e.g. the array west should be a view of a that gives the element at the left
> of location i,j in a.
> a[i,j] = west[i,j+1]
> 
> west can be created using:
> 
> a[:,range(-1,a.shape[1]-1)]
> 
> As you can see, this also defines periodic boundaries (i.e. west[0,0] = 9)
> but it seems that this returns a copy of a, not a view.
> How can I change the slice definition in such a way it returns a view?

You can't get periodic boundary conditions but

a[:,1::]

should give you (part of) the view you are looking for.


-Travis






More information about the Python-list mailing list