Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapping two numpy arrays

Tags:

python

numpy

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

like image 596
ulrich Avatar asked Oct 16 '15 11:10

ulrich


People also ask

How do I connect two NumPy arrays?

Joining means putting contents of two or more arrays in a single array. In SQL we join tables based on a key, whereas in NumPy we join arrays by axes. We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0.

Can you map two arrays?

To map multiple arrays with JavaScript, we can use the map method. to define the zip function that calls a1. map to combine the entries from a1 and a2 with index i into one entry. Then we call zip with arr1 and arr2 to zip them into one array.

Can you add two NumPy arrays?

To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are​ not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.


2 Answers

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')
like image 99
Divakar Avatar answered Sep 20 '22 15:09

Divakar


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')
like image 33
Mazdak Avatar answered Sep 21 '22 15:09

Mazdak