[Numpy-discussion] On responding to dubious ideas (was: Re: Advanced indexing: "fancy" vs. orthogonal)
Jaime Fernández del Río
jaime.frio at gmail.com
Fri Apr 10 13:25:30 EDT 2015
On Fri, Apr 10, 2015 at 9:58 AM, Derek Homeier <
derek at astro.physik.uni-goettingen.de> wrote:
> On 10 Apr 2015, at 06:22 pm, Alan G Isaac <alan.isaac at gmail.com> wrote:
>
> >>
> >> On Thu, Apr 9, 2015 at 8:41 PM, Derek Homeier <
> derek at astro.physik.uni-goettingen.de <mailto:
> derek at astro.physik.uni-goettingen.de>> wrote:
> >> a[1:3,1:3]?
> >> Can’t be generalised to arbitrary selections of rows,columns, though
> (e.g. a[1::2,::2] still works…)
> >
> >
> >
> > On 4/9/2015 11:26 PM, Alexander Belopolsky wrote:
> >> I am interested in the arbitrary selection of rows and columns given by
> indices or by boolean selectors.
> >
> >
> >
> > You mean like this?
> > import numpy as np
> > a = np.arange(20).reshape((4,5))
> > rows = [0,3]
> > cols = [1,2,4]
> > print a[rows][:,cols]
>
> This creates a copy, same apparently with np.ix_ - an objection I had cut
> from the original post…
> Compare to
> b = a[::2,1::2]
> b *= 2
> print(a)
>
Well, the numpy ndarray model requires constant strides along each
dimension, so yes, for consistency fancy indexing always makes a copy. I
believe Alexander's complaint was not that a[[1, 2]][:, [1, 2]] makes one
copy, but that it makes two. Also, with that double fancy indexing approach
you cannot assign to the subarray, something that np.ix_ does enable:
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> a[np.ix_([1, 2], [1, 2])] *= 2
>>> a
array([[ 0, 1, 2, 3],
[ 4, 10, 12, 7],
[ 8, 18, 20, 11],
[12, 13, 14, 15]])
Where it gets complicated is when you have an at least 3D array, and you
want to orthogonally index the first and last dimensions, while extracting
a slice from the middle one. There's no easy answer to that one, and that's
where this whole discussion on modifying numpy's indexing starts to get
some real traction.
Jaime
>
> On 10 Apr 2015, at 02:23 am, Alexander Belopolsky <ndarray at mac.com> wrote:
>
> > I could do
> >
> > >>> a[[1,2]][:,[1,2]]
> > array([[22, 23],
> > [32, 33]])
> >
> > but this creates an extra copy.
> >
> > The best solution I can think of involves something like
> >
> > >>> i = np.array([[1,2]])
> > >>> a.flat[i + len(a)*i.T]
> > array([[22, 23],
> > [32, 33]])
> >
> > which is hardly elegant or obvious.
> >
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
--
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus planes
de dominación mundial.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20150410/eb80828b/attachment.html>
More information about the NumPy-Discussion
mailing list