简体   繁体   English

用各自索引的元组替换多维数组的每个元素

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

In numpy, let's say I have an array k that has shape (2, 3, 2, 2).在 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]]]])

How would I create a new array j of shape (2, 3, 2, 2) such that each element of j is the index of the corresponding value in k ?如何将创建一个新的数组j形状的(2,3,2,2),使得每个元件j是在相应的值的索引k

Example in the first element of the first dimension and first element of the second dimension.第一个维度的第一个元素和第二个维度的第一个元素中的示例。 (Corresponding to (对应于

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

) )

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

.... and so on. .... 等等。

A simple solution would be to iterate over j and explicitly fill each element with its index j[idx, :] = idx :一个简单的解决方案是迭代 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.]]])

The idea is to use np.ndindex as follows:这个想法是使用np.ndindex如下:

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

Result:结果:

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