array view with different shape
Hello List, Can I make a view of an entire array but with a different shape? 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. I know I can simply make a copy of a and change the shape, but can I make b to be a view of a (so that when I change a, then b changes as well)? Thanks, Mark
On Sep 15, 2010, at 11:01 AM, Mark Bakker wrote:
Hello List,
Can I make a view of an entire array but with a different shape?
For example:
a = zeros((2,3,4))
Mark, Try that. b = a.reshape((2,12)) Now,
b.flat=1 a array([[[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]],
[[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]])
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@noaa.gov
participants (3)
-
Christopher Barker -
Mark Bakker -
Pierre GM