简体   繁体   English

Append 元素到每个元素的索引

[英]Append indices of element to each element

So basically I want to create a new array for each element and append the coordinates of the element to the original value (so adding the x and y position to the original element):所以基本上我想为每个元素创建一个新数组,并且 append 将元素的坐标添加到原始值(因此将 x 和 y position 添加到原始元素):

[ [7,2,4],[1,5,3] ]

then becomes然后变成

[ [[0,0,7][0,1,2][0,2,4]],
 [[1,0,1][1,1,5][1,2,3]] ]

I've been looking for different ways to make this work with the axis system in NumPy but I'm probably overseeing some more obvious way.我一直在寻找不同的方法来使这项工作与 NumPy 中的轴系统一起工作,但我可能正在监督一些更明显的方法。

You can try np.meshgrid to create a grid and then np.stack to combine it with input array:您可以尝试np.meshgrid创建一个网格,然后np.stack将其与输入数组组合:

import numpy as np

a = np.asarray([[7,2,4],[1,5,3]])
result = np.stack(np.meshgrid(range(a.shape[1]), range(a.shape[0]))[::-1] + [a], axis=-1)

Output: Output:

array([[[0, 0, 7],
        [0, 1, 2],
        [0, 2, 4]],

       [[1, 0, 1],
        [1, 1, 5],
        [1, 2, 3]]])

Let me know if it helps.让我知道它是否有帮助。

Without numpy you could use list comprehension:如果没有 numpy 您可以使用列表理解:

old_list = [ [7,2,4],[1,5,3] ]
new_list = [ [[i,j,old_list[i][j]] for j in range(len(old_list[i]))] for i in range(old_list) ]

I'd assume that numpy is faster but the sublists are not required to have equal length in this solution.我假设 numpy 更快,但在此解决方案中子列表不需要具有相同的长度。

Another approach using enumerate使用enumerate的另一种方法

In [38]: merge = list()
    ...: for i,j in enumerate(val):
    ...:     merge.append([[i, m, n] for m, n in enumerate(j)])
    ...:

In [39]: merge
Out[39]: [[[0, 0, 7], [0, 1, 2], [0, 2, 4]], [[1, 0, 1], [1, 1, 5], [1, 2, 3]]]

Hope it useful希望有用

a = np.array([[7,2,4], [1,5,3]])
idx = np.argwhere(a)
idx = idx.reshape((*(a.shape), -1))
a = np.expand_dims(a, axis=-1)
a = np.concatenate((idx, a), axis=-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM