numpy中有arange/linspace的多维版本吗? [英] Is there a multi-dimensional version of arange/linspace in numpy?
问题描述
我想要一个2d NumPy数组(x,y)的列表,其中每个x分别位于{-5,-4.5,-4,-3.5,...,3.5、4、4.5、5}中,并且y也一样.
I would like a list of 2d NumPy arrays (x,y) , where each x is in {-5, -4.5, -4, -3.5, ..., 3.5, 4, 4.5, 5} and the same for y.
我可以做到
x = np.arange(-5, 5.1, 0.5)
y = np.arange(-5, 5.1, 0.5)
然后遍历所有可能的对,但是我敢肯定有更好的方法...
and then iterate through all possible pairs, but I'm sure there's a nicer way...
我想要一些看起来像这样的东西
I would like something back that looks like:
[[-5, -5],
[-5, -4.5],
[-5, -4],
...
[5, 5]]
但顺序无关紧要.
推荐答案
您可以使用 np.meshgrid
,因为它一步创建了数组:
You can use np.mgrid
for this, it's often more convenient than np.meshgrid
because it creates the arrays in one step:
import numpy as np
X,Y = np.mgrid[-5:5.1:0.5, -5:5.1:0.5]
要获得类似linspace的功能,请将步骤(即0.5
)替换为一个复数,其大小指定了序列中所需的点数.使用此语法,将与上述相同的数组指定为:
For linspace-like functionality, replace the step (i.e. 0.5
) with a complex number whose magnitude specifies the number of points you want in the series. Using this syntax, the same arrays as above are specified as:
X, Y = np.mgrid[-5:5:21j, -5:5:21j]
然后您可以创建对,如下所示:
You can then create your pairs as:
xy = np.vstack((X.flatten(), Y.flatten())).T
正如@ali_m所建议的,这可以全部在一行中完成:
As @ali_m suggested, this can all be done in one line:
xy = np.mgrid[-5:5.1:0.5, -5:5.1:0.5].reshape(2,-1).T
祝你好运!
这篇关于numpy中有arange/linspace的多维版本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!