[Numpy-discussion] Forcing new dimensions to appear at front in advanced indexing

Michael Lamparski diagonaldevice at gmail.com
Tue Jun 19 19:37:21 EDT 2018


Hi all,

So, in advanced indexing, numpy decides where to put new axes based on
whether the "advanced indices" are all next to each other.

>>> np.random.random((3,4,5,6,7,8))[:, [[0,0],[0,0]], 1, :].shape
(3, 2, 2, 6, 7, 8)
>>> np.random.random((3,4,5,6,7,8))[:, [[0,0],[0,0]], :, 1].shape
(2, 2, 3, 5, 7, 8)

In creating a wrapper type around arrays, I'm finding myself needing to
suppress this behavior, so that the new axes consistently appear in the
front.  I thought of a dumb hat trick:

def index(x, indices):
    return x[(True, None) + indices]

Which certainly gets the new dimensions where I want them, but it
introduces a ghost dimension of 1 (and sometimes two such dimensions!) in a
place where I'm not sure I can easily find it.

>>> np.random.random((3,4,5,6,7,8))[True, None, 1].shape
(1, 1, 4, 5, 6, 7, 8)
>>> np.random.random((3,4,5,6,7,8))[True, None, :, [[0,0],[0,0]], 1,
:].shape
(2, 2, 1, 3, 6, 7, 8)
>>> np.random.random((3,4,5,6,7,8))[True, None, :, [[0,0],[0,0]], :,
1].shape
(2, 2, 1, 3, 5, 7, 8)

any better ideas?

---

Michael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20180619/4d20d518/attachment-0001.html>


More information about the NumPy-Discussion mailing list