用索引位置填充二维 numpy 数组

sto*_*ont 5 python numpy

我一直在尝试找出一种干净的 Pythonic 方法,用该元素的索引值填充空 numpy 数组的每个元素,而不使用 for 循环。对于一维,这很容易,您可以使用类似np.arange或基本的range. 但是在二维和更高维度上,我很难做到这一点。

(编辑:或者只是建立一个像这样的常规列表,然后np.array(lst)它。我想我刚刚回答了我的问题 - 使用列表理解?)

例子:

rows = 4
cols = 4
arr = np.empty((rows, cols, 2))  # 4x4 matrix with [x,y] location

for y in range(rows):
    for x in range(cols):
        arr[y, x] = [y, x]

'''
Expected output:
[[[0,0], [0,1], [0,2], [0,3]],
 [[1,0], [1,1], [1,2], [1,3]],
 [[2,0], [2,1], [2,2], [2,3]],
 [[3,0], [3,1], [3,2], [3,3]]]
'''
Run Code Online (Sandbox Code Playgroud)

Psi*_*dom 5

您显示的是meshgrid4X4 矩阵的 a ;您可以使用np.mgrid,然后转置结果:

np.moveaxis(np.mgrid[:rows,:cols], 0, -1)
#array([[[0, 0],
#        [0, 1],
#        [0, 2],
#        [0, 3]],

#       [[1, 0],
#        [1, 1],
#        [1, 2],
#        [1, 3]],

#       [[2, 0],
#        [2, 1],
#        [2, 2],
#        [2, 3]],

#       [[3, 0],
#        [3, 1],
#        [3, 2],
#        [3, 3]]])
Run Code Online (Sandbox Code Playgroud)

np.meshgrid矩阵索引 一起使用ij

np.dstack(np.meshgrid(np.arange(rows), np.arange(cols), indexing='ij'))
#array([[[0, 0],
#        [0, 1],
#        [0, 2],
#        [0, 3]],

#       [[1, 0],
#        [1, 1],
#        [1, 2],
#        [1, 3]],

#       [[2, 0],
#        [2, 1],
#        [2, 2],
#        [2, 3]],

#       [[3, 0],
#        [3, 1],
#        [3, 2],
#        [3, 3]]])
Run Code Online (Sandbox Code Playgroud)

  • 这是我见过的最简洁的 `np.mgrid` 示例。这些文档对我来说是胡言乱语,我无法从其他 SO 帖子中得出结论。 (2认同)
  • 概括地说,您可以在这里使用 `np.moveaxis`(这是一个特殊的 `transpose`)而不是 `transpose`。它也应该适用于 nd 而无需修改 args。 (2认同)