Q:

Replacing values in array or dataframe

I have a numpy array of values (simplified from a much larger dataset):
data = 
array([[2,  1,  3,  4,]
       [2,  1,  4,  5,]
       [2,  1,  5,  6,]
       [2,  1,  6,  7,]
       [2,  1,  7,  8,]
       [2,  1,  8,  9,]
       [2,  1,  9,  10]])

Which I want to turn into these values:
output =
np.array([[1.2, 0., 2.4, 3.6]
          [1.2, 0., 3.6, 4.8]
          [1.2, 0., 4.8, 6. ]
          [1.2, 0., 6.,  7.2]
          [1.2, 0., 7.2, 8.4]
          [1.2, 0., 8.4, 9. ]
          [1.2, 0., 9.,  9.6]])

I have a lookup array, which I intended to use, but couldn't work out how to use it:
lookup =     
array([[ 1. ,  0. ]
       [ 2. ,  1.2]
       [ 3. ,  2.4]
       [ 4. ,  3.6]
       [ 5. ,  4.8]
       [ 6. ,  6. ]
       [ 7. ,  7.2]
       [ 8. ,  8.4]
       [ 9. ,  9. ]
       [ 10.,  9.6]])

I couldn't work out a way to do this using numpy arrays, so I turned data into a Pandas dataframe:
df = pd.DataFrame(data[:, :], columns=('A', 'B', 'M', 'N'))

df
Out[125]: 
   A  B  M   N
0  2  1  3   4
1  2  1  4   5
2  2  1  5   6
3  2  1  6   7
4  2  1  7   8
5  2  1  8   9
6  2  1  9  10

And tried to convert the values using a dictionary:
di = {1: 0., 2: 1.2, 3: 2.4, 4: 3.6, 5: 4.8, 6: 6., 7: 7.2, 8: 8.4, 9: 9., 10: 9.6}

df.replace({'A': di})
Traceback (most recent call last):

  File "<ipython-input-124-6a329a5fa829>", line 1, in <module>
    df.replace({'A': di})

  File "C:\Users\russells\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py", line 4521, in replace
    raise ValueError("Replacement not allowed with "

ValueError: Replacement not allowed with overlapping keys and values

This obviously didn't work, but also seems like a really clunky, terrible way of approaching the problem. There must be a way of looking up the lookup array rather than writing the dictionary. Does anyone have any pointers?

A:

You need use numpy.vectorize in order to directly map values. 
def mapper(x):
    return lookup[lookup[:,0]==x][:,1][0]

v = np.vectorize(mapper)
data = v(data.astype(float))

Output:
array([[ 1.2,  0. ,  2.4,  3.6],
   [ 1.2,  0. ,  3.6,  4.8],
   [ 1.2,  0. ,  4.8,  6. ],
   [ 1.2,  0. ,  6. ,  7.2],
   [ 1.2,  0. ,  7.2,  8.4],
   [ 1.2,  0. ,  8.4,  9. ],
   [ 1.2,  0. ,  9. ,  9.6]])

