我正在尝试使用numpy.mgrid
创建两个网格数组,但我想要一种方法来插入一个变量作为步数。
使用此代码按预期工作:
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
但是我需要在我自己的代码行中定义我的变量步骤来生成网格数组,我想要这样的东西:
numcols = (xmax-xmin) * 100
numrows = (ymax-ymin) * 100
x, y = np.mgrid[xmin:xmax:(numcols * 1j), ymin:ymax:(numrows * 1j)]
但是,仍然没有工作...... 然后我尝试将步数转换为复数,如下所示:
numcols = (xmax-xmin)
numrows = (ymax-ymin)
x_steps = complex(str(numcols) + "j")
y_steps = complex(str(numrows) + "j")
x, y = np.mgrid[xmin:xmax:x_steps, ymin:ymax:y_steps]
它也不起作用,任何想法?
请注意,我的数据(lat和lon)存储在列表中。
答案 0 :(得分:0)
我不确定你要做什么,但一般来说有两种方法来定义步骤:
如果您希望在100j
中传递100个元素,如果您希望步长1
传入1
(或者因为它是默认值,您也可以省略它)。
您可以随时将它们转换为:
def stepwidth(mini, maxi, nsteps):
return (maxi - mini) / (nsteps - 1)
def nsteps(mini, maxi, stepwidth):
return (maxi - mini) / stepwidth + 1
在我看来,你的计算错了:
>>> xmin = 100
>>> xmax = 200
>>> (xmax-xmin) * 100 * 1j
10000j
这意味着你得到一个10000 * 10000的数组。如果你想在每个整数的网格中有一个数组点,只需使用:
>>> x, y = np.mgrid[xmin:xmax:1, ymin:ymax:1]
或者,如果你想要整数之间的100分(比如乘法100
),请使用:
>>> x, y = np.mgrid[xmin:xmax:0.01, ymin:ymax:0.01]
根据网格的最小点和最大点定义网格点数并没有多大意义。但这正是你所做的并且它正常工作,我只是认为你误认为步宽和步数。
答案 1 :(得分:0)
为了便于说明,我只是做了1d案例
In [285]: xmin, xmax = 0, 10
In [286]: xcol = (xmax-xmin)*10
In [287]: np.mgrid[xmin:xmax:(xcol*1j)]
Out[287]:
array([ 0. , 0.1010101 , 0.2020202 , 0.3030303 ,
0.4040404 , 0.50505051, 0.60606061, 0.70707071,
0.80808081, 0.90909091, 1.01010101, 1.11111111,
...
9.6969697 , 9.7979798 , 9.8989899 , 10. ])
In [288]: len(_)
Out[288]: 100
复杂的步骤方法对我有用。 mgrid
将其转换为linspace
表达式np.linspace(xmin, xmax, 100)
我打算建议非j方法,
In [290]: np.mgrid[xmin:xmax:.1]
Out[290]:
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ,
1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1,
.... 9.4, 9.5, 9.6, 9.7, 9.8,
9.9])
但是它将表达式转换为np.arange(xmin, xmax, .1)
并且确实很好地处理了结束点。
您可能需要调整计数以获得干净的步骤;例如,逐步.1,我们希望将计数从100增加到101。
xcol = (xmax-xmin)*10+1
In [294]: np.linspace(xmin, xmax, xcol)
Out[294]:
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,
... 9.7, 9.8, 9.9, 10. ])
答案 2 :(得分:0)
我发现以下方法可以实现您想要的工作:
x, y = np.mgrid[xmin:xmax:complex(0,100), ymin:ymax:complex(0,100)]
要将变量用作步数,请使用整数变量替换上面表达式中的常数100。例如
x, y = np.mgrid[xmin:xmax:complex(0,i), ymin:ymax:complex(0,k)]
其中i
和k
是整数。