将带有newaxis的多维numpy数组切片存储到对象 [英] Store multidimensional numpy array slice with newaxis to object

查看:61
本文介绍了将带有newaxis的多维numpy数组切片存储到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,需要反复以复杂的方式重复广播数组,例如:

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, :])


也许可以使用 numpy.broadcast_to ,但尚不清楚在确保正确的轴通过...广播时的精确度.


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...

推荐答案

您可以手动构造索引元组,但是NumPy包含

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

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

然后b[np.newaxis, ..., :, np.newaxis]等效于b[slicetuple].

作为参考,手动构造元组为(np.newaxis, Ellipsis, slice(None), np.newaxis).另外,np.newaxis is None,所以(None, Ellipsis, slice(None), None)等效.

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_可以自己重新实现,如下所示:

np.s_ can be reimplemented yourself as follows:

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

s_ = IndexHelper()

这篇关于将带有newaxis的多维numpy数组切片存储到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆