[Numpy-discussion] Why does np.repeat build a full array?

Sebastian Berg sebastian at sipsolutions.net
Tue Dec 15 04:29:07 EST 2015


On Di, 2015-12-15 at 08:56 +0100, Sebastian Berg wrote:
> On Di, 2015-12-15 at 17:49 +1100, Juan Nunez-Iglesias wrote:
> > Hi,
> > 
> > 
> > I've recently been using the following pattern to create arrays of a
> > specific repeating value:
> > 
> > 
> > from numpy.lib.stride_tricks import as_strided
> > 
> > value = np.ones((1,), dtype=float)
> > arr = as_strided(value, shape=input_array.shape, strides=(0,))
> > 
> > 
> > I can then use arr e.g. to count certain pairs of elements using
> > sparse.coo_matrix. It occurred to me that numpy might have a similar
> > function, and found np.repeat. But it seems that repeat actually
> > creates the full, replicated array, rather than using stride tricks to
> > keep it small. Is there any reason for this?
> > 
> 
> Two reasons:
>  1. For most arrays, arrays even the simple repeats cannot be done with
> stride tricks. (yours has a dimension size of 1)
>  2. Stride tricks can be nice, but they can also be
> unexpected/inconsistent when you start writing to the result array, so
> you should not do it (and the array should preferably be read-only IMO,
> as_strided itself does not do that).
> 
> But yes, there might be room for a function or so to make some stride
> tricks more convenient.
> 

Actually, your particular use-case is covered by the new `broadcast_to`
function.


> - Sebastian
> 
> > 
> > Thanks!
> > 
> > 
> > Juan.
> > _______________________________________________
> > NumPy-Discussion mailing list
> > NumPy-Discussion at scipy.org
> > https://mail.scipy.org/mailman/listinfo/numpy-discussion
> 
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> https://mail.scipy.org/mailman/listinfo/numpy-discussion

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20151215/30c7fd31/attachment.sig>


More information about the NumPy-Discussion mailing list