Elements arrangement in Python
Question: Every element of the array "data" have to be changed as follows:

For example, 4 should be seen in names_A and data_A. The names_A for 4 is
'David'. Now 'David' should be seen in names_B and data_B. The data_B for
'David' is 30. So, the element 4 must be changed by 30; and so on.

    
    
    import numpy as np
    
    names_A = ['David', 'Mark', 'Brian', 'Michael']
    data_A = [4,3,1,2]
    
    names_B = ['Mark', 'David', 'Michael', 'Brian']
    data_B = [51,30,11,29]
    
    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]])
    

How is the easiest and simplest way of doing it?

I tried it as follows:

    
    
    dats = data.ravel()
    
    results = []
    for d in dats:
        nam_A = names_A[data_A == int(d)]
        dat_B = data_B[names_B == nam_A]
        results.append(dat_B)
    
    print np.array(results).reshape(data.shape)
    
    
    [[51 51 51 51 51 51 51 51 51 51]
     [51 51 51 51 51 51 51 51 51 51]
     [51 51 51 51 51 51 51 51 51 51]]
    

But, it's giving wrong results. How would you do it?


Answer: 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.

