[Numpy-discussion] array view with different shape

Christopher Barker Chris.Barker at noaa.gov
Wed Sep 15 16:26:06 EDT 2010


Mark Bakker wrote:
> Can I make a view of an entire array but with a different shape?
yup.

> For example:
> 
> a = zeros((2,3,4))
> 
> Now I want array b to be identical to a, but with shape (2,12).
> 
> b = a; b.shape = (2,12)
> 
> This doesn't work, of course, as also the shape of a changes.

as ab and b are bound to the same single object.

someone already gave you reshape(), but for the more general case, 
.view() is handy:

In [11]: a = np.zeros((2,3,4))

In [12]: b = a.view()

In [13]: b.shape = (2, 12)

In [14]: a.shape
Out[14]: (2, 3, 4)

# so they are different objects.

In [15]: a[0,0,0] = 1

In [16]: b
Out[16]:
array([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

# that do share data.

note that .view() can do all sorts of nifty things like change the data 
type or make an np.matrix, or...

-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 at noaa.gov



More information about the NumPy-Discussion mailing list