簡體   English   中英

Numpy切片與數組作為索引

[英]Numpy slice with array as index

我試圖將全套索引提取到一個N維立方體中,似乎np.mgrid正是我需要的。 例如, np.mgrid[0:4,0:4]生成一個4乘4的矩陣,其中包含所有索引到相同形狀的數組中。

問題是我想根據另一個數組的形狀在任意數量的維度中執行此操作。 也就是說,如果我有一個數組a任意尺寸的,我想這樣做idx = np.mgrid[0:a.shape]但語法是不允許的。

是否有可能構建我需要np.mgrid工作的切片? 或者是否有其他一些優雅的方式呢? 以下表達式可以滿足我的需要,但它相當復雜,可能效率不高:

np.reshape(np.array(list(np.ndindex(a.shape))),list(a.shape)+[len(a.shape)])

我通常使用np.indices

>>> a = np.arange(2*3).reshape(2,3)
>>> np.mgrid[:2, :3]
array([[[0, 0, 0],
        [1, 1, 1]],

       [[0, 1, 2],
        [0, 1, 2]]])
>>> np.indices(a.shape)
array([[[0, 0, 0],
        [1, 1, 1]],

       [[0, 1, 2],
        [0, 1, 2]]])
>>> a = np.arange(2*3*5).reshape(2,3,5)
>>> (np.mgrid[:2, :3, :5] == np.indices(a.shape)).all()
True

我相信以下內容符合您的要求:

>>> a = np.random.random((1, 2, 3))
>>> np.mgrid[map(slice, a.shape)]
array([[[[0, 0, 0],
         [0, 0, 0]]],


       [[[0, 0, 0],
         [1, 1, 1]]],


       [[[0, 1, 2],
         [0, 1, 2]]]])

它產生與np.mgrid[0:1,0:2,0:3]完全相同的結果,除了它使用a是形狀而不是硬編碼的尺寸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM