簡體   English   中英

用各自索引的元組替換多維數組的每個元素

[英]Replace each element of multidimensional array with tuple of respective indices

在 numpy 中,假設我有一個形狀為 (2, 3, 2, 2) 的數組k

k = np.array([[[[-0.08759809, -0.10987781],
                [-0.18387192, -0.2109216 ]],

               [[ 0.21027089,  0.21661097],
                [ 0.22847626,  0.23004637]],

               [[ 0.50813986,  0.54309974],
                [ 0.64082444,  0.67101435]]],


              [[[-0.98053589, -1.03143541],
                [-1.19128892, -1.24695841]],

               [[ 0.69108355,  0.66880383],
                [ 0.59480972,  0.56776003]],

               [[ 2.36270298,  2.36904306],
                [ 2.38090835,  2.38247847]]]])

如何將創建一個新的數組j形狀的(2,3,2,2),使得每個元件j是在相應的值的索引k

第一個維度的第一個元素和第二個維度的第一個元素中的示例。 (對應於

[[[[-0.08759809, -0.10987781],
   [-0.18387192, -0.2109216 ]],

)

[[[[(0, 0, 0, 0), (0, 0, 0, 1)],
   [(0, 0, 1, 0), (0, 0, 1, 1)]],

.... 等等。

一個簡單的解決方案是迭代 j 並使用其索引j[idx, :] = idx顯式填充每個元素:

k = np.round(np.random.random((4, 5)), 2)
j = np.empty(k.shape+(k.ndim,))
for idx in np.ndindex(k.shape):
    j[idx, :] = idx

# array([[[0., 0.],
#         [0., 1.],
#         [0., 2.],
#         [0., 3.],
#         [0., 4.]],
#        [[1., 0.],
#         [1., 1.],
#         [1., 2.],
#         [1., 3.],
#         [1., 4.]],
#        [[2., 0.],
#         [2., 1.],
#         [2., 2.],
#         [2., 3.],
#         [2., 4.]],
#        [[3., 0.],
#         [3., 1.],
#         [3., 2.],
#         [3., 3.],
#         [3., 4.]]])

這個想法是使用np.ndindex如下:

j = np.fromiter(np.ndindex(k.shape), dtype='i4,'*k.ndim).reshape(k.shape)

結果:

array([[[[(0, 0, 0, 0), (0, 0, 0, 1)],
          [(0, 0, 1, 0), (0, 0, 1, 1)]],

        [[(0, 1, 0, 0), (0, 1, 0, 1)],
          [(0, 1, 1, 0), (0, 1, 1, 1)]],

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


        [[[(1, 0, 0, 0), (1, 0, 0, 1)],
          [(1, 0, 1, 0), (1, 0, 1, 1)]],

        [[(1, 1, 0, 0), (1, 1, 0, 1)],
          [(1, 1, 1, 0), (1, 1, 1, 1)]],

        [[(1, 2, 0, 0), (1, 2, 0, 1)],
          [(1, 2, 1, 0), (1, 2, 1, 1)]]]],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4')])

暫無
暫無

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

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