在Python中重新编号一维网格

时间:2014-08-07 22:52:45

标签: python arrays numpy

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

我有一个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表指定的相应整数中的每个整数。

2 个答案:

答案 0 :(得分:1)

我实际上无法确切地解决你的问题但是,我尽力帮助你...

我认为你需要替换,例如2替换为1,或者7替换为10,对吗?在这种情况下,您可以为要替换的数字创建字典。 ' dict'以下是为此目的。它也可以通过使用元组或列表来完成,但为此目的,最好使用字典。然后,只需通过查看字典来替换每个元素。

下面的代码是一个非常基本的代码,相对容易理解。肯定有更多的pythonic方法可以做到这一点。但是如果你是Python的新手,下面的代码将是最合适的代码。

import numpy as np

# Data you provided
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]])

# Create a dict for the elements to be replaced
dict = {}
for i_num in range(len(old_num)):
    num = old_num[i_num]
    dict[num] = new_num[i_num]

# Replace the elements
for element in ELEM:
    element[1] = dict[element[1]]
    element[2] = dict[element[2]]

print ELEM

答案 1 :(得分:1)

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

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函数

映射数组的值