5

I have two numpy arrays A and B.

A = np.array ([[ 1  3] [ 2  3]  [ 2  1] ])

B = np.array([(1, 'Alpha'), (2, 'Beta'), (3, 'Gamma')]

How can I map A with B in order to get something like:

result = np.array ([[ 'Alpha'  'Gamma'] [ 'Beta'  'Gamma']  ['Beta'  'Alpha'] ])

I have tried map(B['f1'],A) but I am getting TypeError: 'numpy.ndarray' object is not callable

4 Answers 4

2

Here's a NumPythonic vectorized approach -

B[:,1][(A == B[:,0].astype(int)[:,None,None]).argmax(0)]

Sample run on a generic case -

In [118]: A
Out[118]: 
array([[4, 3],
       [2, 3],
       [2, 4]])

In [119]: B
Out[119]: 
array([['3', 'Alpha'],
       ['4', 'Beta'],
       ['2', 'Gamma']], 
      dtype='|S5')

In [120]: B[:,1][(A == B[:,0].astype(int)[:,None,None]).argmax(0)]
Out[120]: 
array([['Beta', 'Alpha'],
       ['Gamma', 'Alpha'],
       ['Gamma', 'Beta']], 
      dtype='|S5')
Sign up to request clarification or add additional context in comments.

Comments

2

You can use a dictionary and a list comprehension :

>>> d=dict(B)
>>> np.array([[(d[str(i)]),d[str(j)]] for i,j in A])
array([['Alpha', 'Gamma'],
       ['Beta', 'Gamma'],
       ['Beta', 'Alpha']], 
      dtype='|S5')

Comments

2

Without using any specific numpy things you could do:

d = dict(B)
[[d.get(str(y)) for y in x] for x in A]

Comments

1

I assume that you want a numpy solution for efficiency. In this case, try to give your association table a more "numpythonic" appearance :

A = np.array ([[ 1,  3], [ 2,  3] , [ 2,  1] ])
B = np.array([(0,'before'),(1, 'Alpha'), (2, 'Beta'), (3, 'Gamma')])
C=np.array([b[1] for b in B])

Then the result is just : C.take(A).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.