问题描述
我有一个形状为 (A1, M1, A2, M2, A3, M3, E)
的网格,我使用
I have a grid of shape (A1, M1, A2, M2, A3, M3, E)
which I generated using
A1, M1, A2, M2, A3, M3, E = meshgrid(Grid.aGrid, Grid.mGrid, Grid.aGrid, Grid.mGrid, Grid.aGrid, Grid.mGrid, Grid.eGrid, indexing='ij')
,其中 Grid.aGrid
是使用 linspace(aMin, aMax, nA)
生成的,其他网格也类似.
, where Grid.aGrid
is generated using linspace(aMin, aMax, nA)
, and similarly for the other grids.
考虑一些 Z = f(A1, ...)
,其中 f()
会将一些网格点标记为不相关.为简单起见,让它成为
Consider some Z = f(A1, ...)
, where f()
will mark some grid points as irrelevant. For simplicity, let it be
Z = A1 + A2 + A3
Z[Z < 0] = NaN
考虑 Z[0, 1, 2, 3, 4, 5, 6]
.它包含与真实值对应的值 (aGrid[0], mGrid[1], aGrid[2], mGrid[3], aGrid[4], mGrid[5], eGrid[6])代码>.这正是我试图为
Z
上所有没有被 f()
标记的点实现的目标:
Consider Z[0, 1, 2, 3, 4, 5, 6]
. It contains the value corresponding to the real values (aGrid[0], mGrid[1], aGrid[2], mGrid[3], aGrid[4], mGrid[5], eGrid[6])
. This is exactly what I try to achieve for all points on Z
that are not marked by f()
:
我想创建一个字典
foo = {z1, z2, z3, ... zn}
其中 z1
等都是那种
z1 = (aGrid[0], mGrid[1], aGrid[2], mGrid[3], aGrid[4], mGrid[5], eGrid[6])
,即z1
在Z
中的位置对应的grid-values.
, which is the grid-values corresponding to the position of z1
inside Z
.
我想到了一些东西:
aGrid = arange(0, 10)
mGrid = arange(100, 110)
eGrid = arange(1000, 1200)
A,M,E = meshgrid(aGrid, mGrid, eGrid, indexing='ij')
# contains the grid index
Z = (A + M + E).astype(float)
Z[A < 3] = nan
# will contain the actual values, as tuples
Z2 = {}
for i, idx in enumerate(ndindex(Z.shape)):
a = aGrid[idx[0]]
m = mGrid[idx[1]]
e = eGrid[idx[2]]
if isnan(Z[idx]):
Z2[i] = NaN
else:
Z2[i] = (a, m, e)
效率是关键.有没有更快/更清洁的方法可以实现这一目标?除了使用字典,还有其他选择吗?
我特别不喜欢我必须写下aGrid[idx[0]]
等.是否可以使算法更通用?一些类似的事情
I especially dislike that I have to write down aGrid[idx[0]]
etc. Is it possible to keep the algorithm more general? Some thing along the lines of
for i, idx in enumerate(ndindex(Z.shape)):
# some magic happens here. What exactly?
someMagicList = magic(aGrid, mGrid, eGrid)
Z2[i] = someMagicList[idx]
推荐答案
使用broadcast_arrays()
,结果Z2
是一个形状为(20000, 3)
.
Use broadcast_arrays()
, and the result Z2
is an array with shape (20000, 3)
.
import numpy as np
aGrid = np.arange(0, 10, dtype=float)
mGrid = np.arange(100, 110, dtype=float)
eGrid = np.arange(1000, 1200, dtype=float)
A,M,E = np.meshgrid(aGrid, mGrid, eGrid, indexing='ij')
# contains the grid index
Z = (A + M + E).astype(float)
Z[A < 3] = np.nan
grids = [A, M, E]
grid_bc = np.broadcast_arrays(*grids)
Z2 = np.column_stack([g.ravel() for g in grid_bc])
Z2[np.isnan(Z.ravel())] = np.nan
print Z2[5900], Z2[6000]
这篇关于网格索引和实际值之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!