gpt4 book ai didi

python - 在 Python 中对一维网格重新编号

转载 作者:行者123 更新时间:2023-12-01 05:05:09 25 4
gpt4 key购买 nike

首先,我在其他问题中找不到答案。

我有一个整数的 numpy 数组,称为 ELEM,该数组有三列,分别表示元素编号、节点 1 和节点 2。这是一维网格。我需要做的是重新编号节点,我有新旧节点编号表,因此算法应该根据此表替换 ELEM 数组中的每个值。

代码应该是这样的

old_num = np.array([2, 1, 3, 6, 5, 9, 8, 4, 7])
new_num = np.arange(1,10)
ELEM = np.array([ [1, 1, 3], [2, 3, 6], [3, 1, 3], [4, 5, 6]])

从现在开始,对于 ELEM 数组第二列和第三列中的每个元素,我应该替换根据 new_num 表指定的相应整数中的每个整数。

最佳答案

如果您要做很​​多这样的事情,那么在字典中对重新编号进行编码以便快速查找是有意义的。

lookup_table = dict( zip( old_num, new_num ) ) # create your translation dict
vect_lookup = np.vectorize( lookup_table.get ) # create a function to do the translation
ELEM[:, 1:] = vect_lookup( ELEM[:, 1:] ) # Reassign the elements you want to change

np.vectorize 只是为了让语法变得更好。它所做的只是允许我们使用 Lookup_table.get 函数映射数组的值

关于python - 在 Python 中对一维网格重新编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com