Store multidimensional numpy array slice with newa

2019-03-05 02:03发布

I have some code where I repeatedly need to repeatedly broadcast arrays in complex ways, for example:

a = b[np.newaxis, ..., :, np.newaxis] * c[..., np.newaxis, np.newaxis, :]

Is there an object to which I can store these slicing specifications?

i.e. (but obviously this doesn't work):

s1 = magic([np.newaxis, ..., :, np.newaxis])
s2 = magic([..., np.newaxis, np.newaxis, :])

Edit: perhaps this could be done with numpy.broadcast_to, but it's unclear how exactly while making sure that the correct axes are broadcast over...

1条回答
戒情不戒烟
2楼-- · 2019-03-05 03:04

You can construct the index tuple manually, but NumPy includes a helper for it:

slice_tuple = np.s_[np.newaxis, ..., :, np.newaxis]

Then b[np.newaxis, ..., :, np.newaxis] is equivalent to b[slicetuple].


For reference, constructing the tuple manually would be (np.newaxis, Ellipsis, slice(None), np.newaxis). Also, np.newaxis is None, so (None, Ellipsis, slice(None), None) would be equivalent.


np.s_ can be reimplemented yourself as follows:

class IndexHelper(object):
    def __getitem__(self, arg):
        return arg

s_ = IndexHelper()
查看更多
登录 后发表回答