[Numpy-discussion] repeat array along new axis without making a copy
Warren Weckesser
warren.weckesser at enthought.com
Wed Feb 15 07:25:20 EST 2012
On Wed, Feb 15, 2012 at 2:25 AM, Steve Schmerler
<elcortogm at googlemail.com>wrote:
> Hi
>
> I'd like to repeat an array along a new axis (like broadcast):
>
> In [8]: a
> Out[8]:
> array([[0, 1, 2],
> [3, 4, 5]])
> In [9]: b=repeat(a[None,...], 3, axis=0)
> In [10]: b
> Out[10]:
> array([[[0, 1, 2],
> [3, 4, 5]],
>
> [[0, 1, 2],
> [3, 4, 5]],
>
> [[0, 1, 2],
> [3, 4, 5]]])
>
> In [18]: id(a); id(b[0,...]); id(b[1,...]); id(b[2,...])
> Out[18]: 40129600
> Out[18]: 39752080
> Out[18]: 40445232
> Out[18]: 40510272
>
>
> Can I do this such that each sub-array b[i,...] is a view and not a copy?
>
Yes, such an array can be created using the as_strided() function from the
module numpy.lib.stride_tricks:
In [1]: from numpy.lib.stride_tricks import as_strided
In [2]: a = array([[1,2,3],[4,5,6]])
In [3]: b = as_strided(a, strides=(0, a.strides[0], a.strides[1]),
shape=(3, a.shape[0], a.shape[1]))
In [4]: b
Out[4]:
array([[[1, 2, 3],
[4, 5, 6]],
[[1, 2, 3],
[4, 5, 6]],
[[1, 2, 3],
[4, 5, 6]]])
In [5]: a[0,0] = 99
In [6]: b
Out[6]:
array([[[99, 2, 3],
[ 4, 5, 6]],
[[99, 2, 3],
[ 4, 5, 6]],
[[99, 2, 3],
[ 4, 5, 6]]])
Warren
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20120215/3040480a/attachment.html>
More information about the NumPy-Discussion
mailing list