[Numpy-discussion] Inplace reshape

Christopher Barker Chris.Barker@noaa....
Mon Apr 23 12:36:26 CDT 2007


Gael Varoquaux wrote:
> Unless I miss something obvious "a.reshape()" doesn't modify a, which is
> somewhat missleading, IMHO.

quite correct. .reshape() creates a new array that shared data with the 
original:

 >>> import numpy
 >>> a = numpy.zeros((2,3))

 >>> help(a.reshape)
Help on built-in function reshape:

reshape(...)
     a.reshape(d1, d2, ..., dn, order='c')

     Return a new array from this one.  The new array must have the same 

     number of elements as self.  Also always returns a view or raises a
     ValueError if that is impossible.;

 >>> a
array([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])

 >>> b = a.reshape((6,))
 >>> a
array([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])

so a hasn't changed.

 >>> b
array([ 0.,  0.,  0.,  0.,  0.,  0.])

but b is a different shape.

 >>> b[1] = 5
 >>> a
array([[ 0.,  5.,  0.],
        [ 0.,  0.,  0.]])

b and a share data.

if you want to change the shape of a:

 >>> a.shape = (6,)
 >>> a
array([ 0.,  5.,  0.,  0.,  0.,  0.])

-Chris



-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov


More information about the Numpy-discussion mailing list