[英]How to create a multi-dimensional grid in python
我見過類似的問題,但沒有一個需要 output 形狀數組的格式(numpoints, dim)
這是我對dim=2
的簡單示例
import numpy as np
bounds = [0.5, 0.5]
n = [10,10]
dim = 2
x = np.linspace(-bounds[0], bounds[0], n[0])
y = np.linspace(-bounds[1], bounds[1], n[1])
X, Y = np.meshgrid(x, y)
s = X.shape
data = np.zeros((n[0]*n[1],dim))
# convert mesh into point vector for which the model can be evaluated
c = 0
for i in range(s[0]):
for j in range(s[1]):
data[c,0] = X[i,j]
data[c,1] = Y[i,j]
c = c+1;
plt.scatter(data[:,0], data[:,1])
是否有更快/更好的方法來執行此操作,以便以這種方式排列數據? 我想要一種適用於任何dim
的通用方法。
編輯:建議的答案不起作用。
是的,這可以用矢量化
axis_coords = np.meshgrid(x, y, indexing='xy')
data = np.hstack([c.reshape(-1, 1) for c in axis_coords])
c.reshape(-1, 1)
只是將c
從 ( HxW
到(H*W)x1
) 重塑,以便可以水平堆疊。
注意 - 如果您希望推廣到更多的暗淡,您可能想要切換到indexing='ij'
所以它按 (row, column, dim2, dim3, ...) 而不是 (column, row, dim2, dim3 , ...) 因為在 numpy 中,行被認為是第 0 維,列被認為是第 1 維。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.