[Numpy-discussion] Views and Increments
Sebastian Berg
sebastian at sipsolutions.net
Mon Aug 8 09:21:15 EDT 2016
On Mo, 2016-08-08 at 15:11 +0200, Anakim Border wrote:
> Dear List,
>
> I'm experimenting with views and array indexing. I have written two
> code blocks that I was expecting to produce the same result.
>
> First try:
>
> >>> a = np.arange(10)
> >>> b = a[np.array([1,6,5])]
> >>> b += 1
> >>> a
> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>
>
> Alternative version:
>
> >>> a = np.arange(10)
> >>> a[np.array([1,6,5])] += 1
> >>> a
> array([0, 2, 2, 3, 4, 6, 7, 7, 8, 9])
>
>
> I understand what is happening in the first case. In fact, the
> documentation is quite clear on the subject:
>
> For all cases of index arrays, what is returned is a copy of the
> original data, not a view as one gets for slices.
>
> What about the second case? There, I'm not keeping a reference to the
> intermediate copy (b, in the first example). Still, I don't see why
> the update (to the copy) is propagating to the original array. Is
> there any implementation detail that I'm missing?
>
The second case translates to:
tmp = a[np.array([1,6,5])] + 1
a[np.array([1,6,5])] = tmp
this is done by python, without any interplay of numpy at all. Which is
different from `arr += 1`, which is specifically defined and translates
to `np.add(arr, 1, out=arr)`.
- Sebastian
> Best,
> ab
> _______________________________________________
> 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/20160808/f15caa1e/attachment.sig>
More information about the NumPy-Discussion
mailing list