Reputation: 3587
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
Upvotes: 5
Views: 4512
Reputation: 18668
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)
.
Upvotes: 1
Reputation: 221774
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')
Upvotes: 2
Reputation: 4395
Without using any specific numpy things you could do:
d = dict(B)
[[d.get(str(y)) for y in x] for x in A]
Upvotes: 2
Reputation: 107357
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')
Upvotes: 2