我有以下问题,到目前为止我还没有找到任何有用的提示。
我有两个看起来像这样的数组:
sample_nodes = [[ ID_1 x1 y1 z1]
[ ID_2 x2 y2 z2]
[ ID_3 x3 y3 z4]
.
.
.
[ ID_n xn yn zn]]
和
sample_elements = [[[ ID_7 0 0 0]
[ ID_21 0 0 0]
[ ID_991 0 0 0]
[ ID_34 0 0 0]]
[[ ID_67 0 0 0]
[ ID_1 0 0 0]
[ ID_42 0 0 0]
[ ID_15 0 0 0]]
.
.
.
[[ ID_33 0 0 0]
[ ID_42 0 0 0]
[ ID_82 0 0 0]
[ ID_400 0 0 0]]]
sample_nodes具有sample_elements所需的x,y和z坐标,其中ID以随机顺序排列。因此,我必须查看sample_elements数组中每行的每个ID,并从sample_nodes中找出相应的x,y和z坐标,并在与ID对应的sample_elements数组中再次替换零值。
我对python和numpy都很新,因此,不知道如何解决这个问题。在此先感谢各位有兴趣解决这个问题的人。
此外,sample_elements中的所有ID都存在于sample_nodes中。只有在sample_elements中它们才是随机排列的,因为它们是由一个名为Gmsh的网格化软件生成的。我实际上是在尝试解析它的输出网格文件。
答案 0 :(得分:1)
您可以使用np.searchsorted
来形成原始行顺序,然后只需将其编入sample_nodes
即可为我们提供所需的输出。因此,我们会有这样的实现 -
sample_nodes[np.searchsorted(sample_nodes[:,0],sample_elements[:,0])]
示例运行 -
In [80]: sample_nodes
Out[80]:
array([[1, 3, 3, 6],
[3, 2, 4, 8],
[4, 2, 3, 4],
[5, 3, 0, 8],
[6, 8, 2, 3],
[7, 4, 6, 3],
[8, 3, 8, 4]])
In [81]: sample_elements
Out[81]:
array([[7, 0, 0, 0],
[5, 0, 0, 0],
[3, 0, 0, 0],
[6, 0, 0, 0]])
In [82]: sample_nodes[np.searchsorted(sample_nodes[:,0],sample_elements[:,0])]
Out[82]:
array([[7, 4, 6, 3],
[5, 3, 0, 8],
[3, 2, 4, 8],
[6, 8, 2, 3]])
如果IDs
中的sample_nodes
未按排序顺序排列,我们需要将sorter
与np.searchsorted
一起使用,如此 -
sidx = sample_nodes[:,0].argsort()
row_idx = np.searchsorted(sample_nodes[:,0],sample_elements[:,0],sorter=sidx)
out = sample_nodes[sidx[row_idx]]
示例运行 -
In [98]: sample_nodes
Out[98]:
array([[3, 3, 3, 6],
[5, 2, 4, 8],
[8, 2, 3, 4],
[1, 3, 0, 8],
[4, 8, 2, 3],
[7, 4, 6, 3],
[6, 3, 8, 4]])
In [99]: sample_elements
Out[99]:
array([[7, 0, 0, 0],
[5, 0, 0, 0],
[3, 0, 0, 0],
[6, 0, 0, 0]])
In [100]: out
Out[100]:
array([[7, 4, 6, 3],
[5, 2, 4, 8],
[3, 3, 3, 6],
[6, 3, 8, 4]])
答案 1 :(得分:1)
numpy_indexed包具有解决问题关键步骤的功能(在另一个序列中找到一个序列的索引)。如果你不熟悉numpy,并且关心效率,请务必仔细阅读!
import numpy as np
import numpy_indexed as npi
sample_nodes = np.asarray(sample_nodes)
sample_elements = np.asarray(sample_elements)
idx = npi.indices(sample_nodes[:, 0], sample_elements[:, 0])
sample_elements[:, 1:] = sample_nodes[idx, 1:]