我一直在尝试找出一种干净的 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)
您显示的是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)
| 归档时间: |
|
| 查看次数: |
3227 次 |
| 最近记录: |