Elements arrangement in Python

那年仲夏 提交于 2019-12-02 14:54:13

Use dictionaries to create a mapping.

names_A = ['David', 'Mark', 'Brian', 'Michael']
data_A = [4,3,1,2]

names_B = ['Mark', 'David', 'Michael', 'Brian']
data_B = [51,30,11,29]

lookup_a = dict(zip(names_A, data_A))
lookup_b = dict(zip(names_B, data_B))

mapping = {value_a: lookup_b[key_a] for key_a, value_a in lookup_a.items()}

Now the keys in mapping will be the numbers from data_A with the corresponding values from data_B.

I never worked with numpy but it looks like an easy task to do the replacement now.


Just to give an example with a simple list:

data = [4, 4, 3, 3, 2, 2, 1, 1, 3, 3]
data = [mapping[value] for value in data]

data now is [30, 30, 51, 51, 11, 11, 29, 29, 51, 51].


Edited after installing numpy

If you created the mapping dictionary you can do the following:

data = np.array([[4, 4, 3, 3, 2, 2, 1, 1, 3, 3],
                 [4, 3, 3, 3, 2, 2, 3, 1, 3, 1],
                 [4, 2, 3, 3, 2, 2, 4, 1, 4, 3]])

for row in data:
    for index, value in enumerate(row):
        row[index] = mapping[value]

data is now:

[[32 30 51 51 11 11 29 29 51 51]
 [30 51 51 51 11 11 51 29 51 29]
 [30 11 51 51 11 11 30 29 30 51]]

As I never worked with numpy before there might be easier (or more pythonic) solutions, but at least this does what it should do.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!